Tweak previos change
[bpt/emacs.git] / lisp / gnus / auth-source.el
CommitLineData
8f7abae3
MB
1;;; auth-source.el --- authentication sources for Gnus and Emacs
2
ab422c4d 3;; Copyright (C) 2008-2013 Free Software Foundation, Inc.
8f7abae3
MB
4
5;; Author: Ted Zlatanov <tzz@lifelogs.com>
6;; Keywords: news
7
8;; This file is part of GNU Emacs.
9
5e809f55 10;; GNU Emacs is free software: you can redistribute it and/or modify
8f7abae3 11;; it under the terms of the GNU General Public License as published by
5e809f55
GM
12;; the Free Software Foundation, either version 3 of the License, or
13;; (at your option) any later version.
8f7abae3
MB
14
15;; GNU Emacs is distributed in the hope that it will be useful,
16;; but WITHOUT ANY WARRANTY; without even the implied warranty of
5e809f55 17;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
8f7abae3
MB
18;; GNU General Public License for more details.
19
20;; You should have received a copy of the GNU General Public License
5e809f55 21;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
8f7abae3
MB
22
23;;; Commentary:
24
25;; This is the auth-source.el package. It lets users tell Gnus how to
26;; authenticate in a single place. Simplicity is the goal. Instead
27;; of providing 5000 options, we'll stick to simple, easy to
28;; understand options.
d55fe5bb 29
554a69b8 30;; See the auth.info Info documentation for details.
4079589f 31
cbabe91f
TZ
32;; TODO:
33
34;; - never decode the backend file unless it's necessary
35;; - a more generic way to match backends and search backend contents
36;; - absorb netrc.el and simplify it
37;; - protect passwords better
38;; - allow creating and changing netrc lines (not files) e.g. change a password
39
8f7abae3
MB
40;;; Code:
41
b8e0f0cd 42(require 'password-cache)
d638ac9e 43(require 'mm-util)
e952b711 44(require 'gnus-util)
936d08bb 45
8f7abae3 46(eval-when-compile (require 'cl))
b68bbc23 47(require 'eieio)
b8e0f0cd 48
0e4966fb
MA
49(autoload 'secrets-create-item "secrets")
50(autoload 'secrets-delete-item "secrets")
ec7995fa 51(autoload 'secrets-get-alias "secrets")
b8e0f0cd 52(autoload 'secrets-get-attributes "secrets")
fb178e4c 53(autoload 'secrets-get-secret "secrets")
0e4966fb
MA
54(autoload 'secrets-list-collections "secrets")
55(autoload 'secrets-search-items "secrets")
8f7abae3 56
4248cca2
TZ
57(autoload 'rfc2104-hash "rfc2104")
58
8977de27
DU
59(autoload 'plstore-open "plstore")
60(autoload 'plstore-find "plstore")
61(autoload 'plstore-put "plstore")
f3078a00 62(autoload 'plstore-delete "plstore")
8977de27 63(autoload 'plstore-save "plstore")
c302199d 64(autoload 'plstore-get-file "plstore")
8977de27 65
b09c3fe0
G
66(autoload 'epg-make-context "epg")
67(autoload 'epg-context-set-passphrase-callback "epg")
68(autoload 'epg-decrypt-string "epg")
69(autoload 'epg-context-set-armor "epg")
70(autoload 'epg-encrypt-string "epg")
71
b0de839f
KY
72(autoload 'help-mode "help-mode" nil t)
73
b8e0f0cd
G
74(defvar secrets-enabled)
75
8f7abae3
MB
76(defgroup auth-source nil
77 "Authentication sources."
9b3ebcb6 78 :version "23.1" ;; No Gnus
8f7abae3
MB
79 :group 'gnus)
80
584c9d3f
G
81;;;###autoload
82(defcustom auth-source-cache-expiry 7200
83 "How many seconds passwords are cached, or nil to disable
84expiring. Overrides `password-cache-expiry' through a
85let-binding."
2bed3f04 86 :version "24.1"
584c9d3f
G
87 :group 'auth-source
88 :type '(choice (const :tag "Never" nil)
89 (const :tag "All Day" 86400)
90 (const :tag "2 Hours" 7200)
91 (const :tag "30 Minutes" 1800)
92 (integer :tag "Seconds")))
93
cbffd0bd
SM
94;; The slots below correspond with the `auth-source-search' spec,
95;; so a backend with :host set, for instance, would match only
96;; searches for that host. Normally they are nil.
b8e0f0cd
G
97(defclass auth-source-backend ()
98 ((type :initarg :type
99 :initform 'netrc
100 :type symbol
101 :custom symbol
102 :documentation "The backend type.")
103 (source :initarg :source
104 :type string
105 :custom string
106 :documentation "The backend source.")
107 (host :initarg :host
108 :initform t
109 :type t
110 :custom string
111 :documentation "The backend host.")
112 (user :initarg :user
113 :initform t
114 :type t
115 :custom string
116 :documentation "The backend user.")
35123c04
TZ
117 (port :initarg :port
118 :initform t
119 :type t
120 :custom string
121 :documentation "The backend protocol.")
65afde5c 122 (data :initarg :data
b09c3fe0
G
123 :initform nil
124 :documentation "Internal backend data.")
b8e0f0cd
G
125 (create-function :initarg :create-function
126 :initform ignore
127 :type function
128 :custom function
129 :documentation "The create function.")
130 (search-function :initarg :search-function
131 :initform ignore
132 :type function
133 :custom function
134 :documentation "The search function.")))
135
9b3ebcb6 136(defcustom auth-source-protocols '((imap "imap" "imaps" "143" "993")
cbabe91f
TZ
137 (pop3 "pop3" "pop" "pop3s" "110" "995")
138 (ssh "ssh" "22")
139 (sftp "sftp" "115")
140 (smtp "smtp" "25"))
9b3ebcb6
MB
141 "List of authentication protocols and their names"
142
143 :group 'auth-source
ec7995fa 144 :version "23.2" ;; No Gnus
9b3ebcb6 145 :type '(repeat :tag "Authentication Protocols"
cbabe91f
TZ
146 (cons :tag "Protocol Entry"
147 (symbol :tag "Protocol")
148 (repeat :tag "Names"
149 (string :tag "Name")))))
9b3ebcb6 150
cbffd0bd
SM
151;; Generate all the protocols in a format Customize can use.
152;; TODO: generate on the fly from auth-source-protocols
9b3ebcb6
MB
153(defconst auth-source-protocols-customize
154 (mapcar (lambda (a)
cbabe91f
TZ
155 (let ((p (car-safe a)))
156 (list 'const
157 :tag (upcase (symbol-name p))
158 p)))
159 auth-source-protocols))
9b3ebcb6 160
b8e0f0cd
G
161(defvar auth-source-creation-defaults nil
162 "Defaults for creating token values. Usually let-bound.")
163
003522ce
G
164(defvar auth-source-creation-prompts nil
165 "Default prompts for token values. Usually let-bound.")
166
b8e0f0cd
G
167(make-obsolete 'auth-source-hide-passwords nil "Emacs 24.1")
168
003522ce
G
169(defcustom auth-source-save-behavior 'ask
170 "If set, auth-source will respect it for save behavior."
171 :group 'auth-source
172 :version "23.2" ;; No Gnus
173 :type `(choice
174 :tag "auth-source new token save behavior"
175 (const :tag "Always save" t)
176 (const :tag "Never save" nil)
177 (const :tag "Ask" ask)))
178
61e6a0ac
TZ
179;; TODO: make the default (setq auth-source-netrc-use-gpg-tokens `((,(if (boundp 'epa-file-auto-mode-alist-entry) (car (symbol-value 'epa-file-auto-mode-alist-entry)) "\\.gpg\\'") never) (t gpg)))
180;; TODO: or maybe leave as (setq auth-source-netrc-use-gpg-tokens 'never)
181
182(defcustom auth-source-netrc-use-gpg-tokens 'never
183 "Set this to tell auth-source when to create GPG password
b09c3fe0
G
184tokens in netrc files. It's either an alist or `never'.
185Note that if EPA/EPG is not available, this should NOT be used."
2b8c5660
TZ
186 :group 'auth-source
187 :version "23.2" ;; No Gnus
188 :type `(choice
61e6a0ac
TZ
189 (const :tag "Always use GPG password tokens" (t gpg))
190 (const :tag "Never use GPG password tokens" never)
191 (repeat :tag "Use a lookup list"
192 (list
193 (choice :tag "Matcher"
194 (const :tag "Match anything" t)
195 (const :tag "The EPA encrypted file extensions"
196 ,(if (boundp 'epa-file-auto-mode-alist-entry)
197 (car (symbol-value
198 'epa-file-auto-mode-alist-entry))
199 "\\.gpg\\'"))
200 (regexp :tag "Regular expression"))
201 (choice :tag "What to do"
202 (const :tag "Save GPG-encrypted password tokens" gpg)
203 (const :tag "Don't encrypt tokens" never))))))
2b8c5660 204
b8e0f0cd 205(defvar auth-source-magic "auth-source-magic ")
ed778fad
MB
206
207(defcustom auth-source-do-cache t
b8e0f0cd 208 "Whether auth-source should cache information with `password-cache'."
ed778fad 209 :group 'auth-source
ec7995fa 210 :version "23.2" ;; No Gnus
ed778fad
MB
211 :type `boolean)
212
a202ff49 213(defcustom auth-source-debug nil
554a69b8 214 "Whether auth-source should log debug messages.
554a69b8
KY
215
216If the value is nil, debug messages are not logged.
ca6ddb88
TZ
217
218If the value is t, debug messages are logged with `message'. In
219that case, your authentication data will be in the clear (except
220for passwords).
221
554a69b8
KY
222If the value is a function, debug messages are logged by calling
223 that function using the same arguments as `message'."
224 :group 'auth-source
ec7995fa 225 :version "23.2" ;; No Gnus
cbabe91f
TZ
226 :type `(choice
227 :tag "auth-source debugging mode"
228 (const :tag "Log using `message' to the *Messages* buffer" t)
4a3988d5
G
229 (const :tag "Log all trivia with `message' to the *Messages* buffer"
230 trivia)
cbabe91f
TZ
231 (function :tag "Function that takes arguments like `message'")
232 (const :tag "Don't log anything" nil)))
554a69b8 233
6a6e4d93 234(defcustom auth-sources '("~/.authinfo" "~/.authinfo.gpg" "~/.netrc")
8f7abae3
MB
235 "List of authentication sources.
236
b8e0f0cd
G
237The default will get login and password information from
238\"~/.authinfo.gpg\", which you should set up with the EPA/EPG
239packages to be encrypted. If that file doesn't exist, it will
4a3988d5
G
240try the unencrypted version \"~/.authinfo\" and the famous
241\"~/.netrc\" file.
b8e0f0cd
G
242
243See the auth.info manual for details.
fb178e4c 244
ec7995fa
KY
245Each entry is the authentication type with optional properties.
246
247It's best to customize this with `M-x customize-variable' because the choices
248can get pretty complex."
8f7abae3 249 :group 'auth-source
b8e0f0cd 250 :version "24.1" ;; No Gnus
9b3ebcb6 251 :type `(repeat :tag "Authentication Sources"
b8e0f0cd
G
252 (choice
253 (string :tag "Just a file")
254 (const :tag "Default Secrets API Collection" 'default)
5415d076 255 (const :tag "Login Secrets API Collection" "secrets:Login")
b8e0f0cd 256 (const :tag "Temp Secrets API Collection" "secrets:session")
d7fcec5d
TZ
257
258 (const :tag "Default internet Mac OS Keychain"
c20643e2 259 macos-keychain-internet)
d7fcec5d
TZ
260
261 (const :tag "Default generic Mac OS Keychain"
c20643e2 262 macos-keychain-generic)
d7fcec5d 263
b8e0f0cd
G
264 (list :tag "Source definition"
265 (const :format "" :value :source)
266 (choice :tag "Authentication backend choice"
267 (string :tag "Authentication Source (file)")
268 (list
269 :tag "Secret Service API/KWallet/GNOME Keyring"
270 (const :format "" :value :secrets)
271 (choice :tag "Collection to use"
272 (string :tag "Collection name")
273 (const :tag "Default" 'default)
5415d076 274 (const :tag "Login" "Login")
b8e0f0cd 275 (const
d7fcec5d
TZ
276 :tag "Temporary" "session")))
277 (list
278 :tag "Mac OS internet Keychain"
279 (const :format ""
280 :value :macos-keychain-internet)
281 (choice :tag "Collection to use"
282 (string :tag "internet Keychain path")
d6e7c17b 283 (const :tag "default" 'default)))
d7fcec5d
TZ
284 (list
285 :tag "Mac OS generic Keychain"
286 (const :format ""
287 :value :macos-keychain-generic)
288 (choice :tag "Collection to use"
289 (string :tag "generic Keychain path")
290 (const :tag "default" 'default))))
b8e0f0cd
G
291 (repeat :tag "Extra Parameters" :inline t
292 (choice :tag "Extra parameter"
293 (list
294 :tag "Host"
295 (const :format "" :value :host)
296 (choice :tag "Host (machine) choice"
297 (const :tag "Any" t)
298 (regexp
299 :tag "Regular expression")))
300 (list
301 :tag "Protocol"
35123c04 302 (const :format "" :value :port)
b8e0f0cd
G
303 (choice
304 :tag "Protocol"
305 (const :tag "Any" t)
306 ,@auth-source-protocols-customize))
307 (list :tag "User" :inline t
308 (const :format "" :value :user)
61e6a0ac
TZ
309 (choice
310 :tag "Personality/Username"
e9cb4479
DU
311 (const :tag "Any" t)
312 (string
313 :tag "Name")))))))))
8f7abae3 314
549c9aed
G
315(defcustom auth-source-gpg-encrypt-to t
316 "List of recipient keys that `authinfo.gpg' encrypted to.
317If the value is not a list, symmetric encryption will be used."
318 :group 'auth-source
b8e0f0cd 319 :version "24.1" ;; No Gnus
549c9aed 320 :type '(choice (const :tag "Symmetric encryption" t)
b8e0f0cd
G
321 (repeat :tag "Recipient public keys"
322 (string :tag "Recipient public key"))))
549c9aed 323
8f7abae3 324;; temp for debugging
9b3ebcb6
MB
325;; (unintern 'auth-source-protocols)
326;; (unintern 'auth-sources)
327;; (customize-variable 'auth-sources)
328;; (setq auth-sources nil)
329;; (format "%S" auth-sources)
330;; (customize-variable 'auth-source-protocols)
331;; (setq auth-source-protocols nil)
332;; (format "%S" auth-source-protocols)
fb178e4c 333;; (auth-source-pick nil :host "a" :port 'imap)
9b3ebcb6
MB
334;; (auth-source-user-or-password "login" "imap.myhost.com" 'imap)
335;; (auth-source-user-or-password "password" "imap.myhost.com" 'imap)
336;; (auth-source-user-or-password-imap "login" "imap.myhost.com")
337;; (auth-source-user-or-password-imap "password" "imap.myhost.com")
338;; (auth-source-protocol-defaults 'imap)
339
ca6ddb88
TZ
340;; (let ((auth-source-debug 'debug)) (auth-source-do-debug "hello"))
341;; (let ((auth-source-debug t)) (auth-source-do-debug "hello"))
342;; (let ((auth-source-debug nil)) (auth-source-do-debug "hello"))
554a69b8 343(defun auth-source-do-debug (&rest msg)
554a69b8 344 (when auth-source-debug
ca6ddb88
TZ
345 (apply 'auth-source-do-warn msg)))
346
4a3988d5
G
347(defun auth-source-do-trivia (&rest msg)
348 (when (or (eq auth-source-debug 'trivia)
349 (functionp auth-source-debug))
350 (apply 'auth-source-do-warn msg)))
351
ca6ddb88
TZ
352(defun auth-source-do-warn (&rest msg)
353 (apply
e9cb4479
DU
354 ;; set logger to either the function in auth-source-debug or 'message
355 ;; note that it will be 'message if auth-source-debug is nil
ca6ddb88
TZ
356 (if (functionp auth-source-debug)
357 auth-source-debug
358 'message)
359 msg))
360
554a69b8 361
cbffd0bd 362;; (auth-source-read-char-choice "enter choice? " '(?a ?b ?q))
733afdf4
TZ
363(defun auth-source-read-char-choice (prompt choices)
364 "Read one of CHOICES by `read-char-choice', or `read-char'.
365`dropdown-list' support is disabled because it doesn't work reliably.
366Only one of CHOICES will be returned. The PROMPT is augmented
367with \"[a/b/c] \" if CHOICES is '\(?a ?b ?c\)."
368 (when choices
369 (let* ((prompt-choices
370 (apply 'concat (loop for c in choices
371 collect (format "%c/" c))))
372 (prompt-choices (concat "[" (substring prompt-choices 0 -1) "] "))
373 (full-prompt (concat prompt prompt-choices))
374 k)
375
376 (while (not (memq k choices))
377 (setq k (cond
733afdf4
TZ
378 ((fboundp 'read-char-choice)
379 (read-char-choice full-prompt choices))
380 (t (message "%s" full-prompt)
381 (setq k (read-char))))))
382 k)))
383
35123c04
TZ
384;; (auth-source-pick nil :host "any" :port 'imap :user "joe")
385;; (auth-source-pick t :host "any" :port 'imap :user "joe")
386;; (setq auth-sources '((:source (:secrets default) :host t :port t :user "joe")
387;; (:source (:secrets "session") :host t :port t :user "joe")
388;; (:source (:secrets "Login") :host t :port t)
389;; (:source "~/.authinfo.gpg" :host t :port t)))
fb178e4c 390
35123c04
TZ
391;; (setq auth-sources '((:source (:secrets default) :host t :port t :user "joe")
392;; (:source (:secrets "session") :host t :port t :user "joe")
393;; (:source (:secrets "Login") :host t :port t)
cbabe91f 394;; ))
fb178e4c 395
35123c04 396;; (setq auth-sources '((:source "~/.authinfo.gpg" :host t :port t)))
fb178e4c 397
b8e0f0cd
G
398;; (auth-source-backend-parse "myfile.gpg")
399;; (auth-source-backend-parse 'default)
5415d076 400;; (auth-source-backend-parse "secrets:Login")
d7fcec5d
TZ
401;; (auth-source-backend-parse 'macos-keychain-internet)
402;; (auth-source-backend-parse 'macos-keychain-generic)
403;; (auth-source-backend-parse "macos-keychain-internet:/path/here.keychain")
404;; (auth-source-backend-parse "macos-keychain-generic:/path/here.keychain")
b8e0f0cd
G
405
406(defun auth-source-backend-parse (entry)
407 "Creates an auth-source-backend from an ENTRY in `auth-sources'."
408 (auth-source-backend-parse-parameters
409 entry
410 (cond
411 ;; take 'default and recurse to get it as a Secrets API default collection
412 ;; matching any user, host, and protocol
413 ((eq entry 'default)
414 (auth-source-backend-parse '(:source (:secrets default))))
415 ;; take secrets:XYZ and recurse to get it as Secrets API collection "XYZ"
416 ;; matching any user, host, and protocol
417 ((and (stringp entry) (string-match "^secrets:\\(.+\\)" entry))
418 (auth-source-backend-parse `(:source (:secrets ,(match-string 1 entry)))))
d7fcec5d
TZ
419
420 ;; take 'macos-keychain-internet and recurse to get it as a Mac OS
421 ;; Keychain collection matching any user, host, and protocol
422 ((eq entry 'macos-keychain-internet)
423 (auth-source-backend-parse '(:source (:macos-keychain-internet default))))
424 ;; take 'macos-keychain-generic and recurse to get it as a Mac OS
425 ;; Keychain collection matching any user, host, and protocol
426 ((eq entry 'macos-keychain-generic)
427 (auth-source-backend-parse '(:source (:macos-keychain-generic default))))
428 ;; take macos-keychain-internet:XYZ and recurse to get it as MacOS
429 ;; Keychain "XYZ" matching any user, host, and protocol
430 ((and (stringp entry) (string-match "^macos-keychain-internet:\\(.+\\)"
431 entry))
432 (auth-source-backend-parse `(:source (:macos-keychain-internet
433 ,(match-string 1 entry)))))
434 ;; take macos-keychain-generic:XYZ and recurse to get it as MacOS
435 ;; Keychain "XYZ" matching any user, host, and protocol
436 ((and (stringp entry) (string-match "^macos-keychain-generic:\\(.+\\)"
437 entry))
438 (auth-source-backend-parse `(:source (:macos-keychain-generic
439 ,(match-string 1 entry)))))
440
b8e0f0cd
G
441 ;; take just a file name and recurse to get it as a netrc file
442 ;; matching any user, host, and protocol
443 ((stringp entry)
444 (auth-source-backend-parse `(:source ,entry)))
445
446 ;; a file name with parameters
447 ((stringp (plist-get entry :source))
8977de27 448 (if (equal (file-name-extension (plist-get entry :source)) "plist")
e9cb4479
DU
449 (auth-source-backend
450 (plist-get entry :source)
451 :source (plist-get entry :source)
452 :type 'plstore
453 :search-function 'auth-source-plstore-search
454 :create-function 'auth-source-plstore-create
455 :data (plstore-open (plist-get entry :source)))
8977de27 456 (auth-source-backend
e9cb4479
DU
457 (plist-get entry :source)
458 :source (plist-get entry :source)
459 :type 'netrc
460 :search-function 'auth-source-netrc-search
461 :create-function 'auth-source-netrc-create)))
b8e0f0cd 462
d7fcec5d
TZ
463 ;; the MacOS Keychain
464 ((and
465 (not (null (plist-get entry :source))) ; the source must not be nil
466 (listp (plist-get entry :source)) ; and it must be a list
467 (or
468 (plist-get (plist-get entry :source) :macos-keychain-generic)
469 (plist-get (plist-get entry :source) :macos-keychain-internet)))
470
471 (let* ((source-spec (plist-get entry :source))
472 (keychain-generic (plist-get source-spec :macos-keychain-generic))
473 (keychain-type (if keychain-generic
474 'macos-keychain-generic
475 'macos-keychain-internet))
476 (source (plist-get source-spec (if keychain-generic
477 :macos-keychain-generic
478 :macos-keychain-internet))))
479
480 (when (symbolp source)
481 (setq source (symbol-name source)))
482
483 (auth-source-backend
484 (format "Mac OS Keychain (%s)" source)
485 :source source
486 :type keychain-type
487 :search-function 'auth-source-macos-keychain-search
488 :create-function 'auth-source-macos-keychain-create)))
489
b8e0f0cd
G
490 ;; the Secrets API. We require the package, in order to have a
491 ;; defined value for `secrets-enabled'.
492 ((and
493 (not (null (plist-get entry :source))) ; the source must not be nil
494 (listp (plist-get entry :source)) ; and it must be a list
495 (require 'secrets nil t) ; and we must load the Secrets API
496 secrets-enabled) ; and that API must be enabled
497
498 ;; the source is either the :secrets key in ENTRY or
499 ;; if that's missing or nil, it's "session"
500 (let ((source (or (plist-get (plist-get entry :source) :secrets)
501 "session")))
502
503 ;; if the source is a symbol, we look for the alias named so,
5415d076 504 ;; and if that alias is missing, we use "Login"
b8e0f0cd
G
505 (when (symbolp source)
506 (setq source (or (secrets-get-alias (symbol-name source))
5415d076 507 "Login")))
b8e0f0cd 508
ca6ddb88
TZ
509 (if (featurep 'secrets)
510 (auth-source-backend
511 (format "Secrets API (%s)" source)
512 :source source
513 :type 'secrets
514 :search-function 'auth-source-secrets-search
515 :create-function 'auth-source-secrets-create)
516 (auth-source-do-warn
517 "auth-source-backend-parse: no Secrets API, ignoring spec: %S" entry)
518 (auth-source-backend
519 (format "Ignored Secrets API (%s)" source)
520 :source ""
521 :type 'ignore))))
b8e0f0cd
G
522
523 ;; none of them
524 (t
ca6ddb88 525 (auth-source-do-warn
b8e0f0cd
G
526 "auth-source-backend-parse: invalid backend spec: %S" entry)
527 (auth-source-backend
528 "Empty"
529 :source ""
530 :type 'ignore)))))
531
532(defun auth-source-backend-parse-parameters (entry backend)
533 "Fills in the extra auth-source-backend parameters of ENTRY.
35123c04
TZ
534Using the plist ENTRY, get the :host, :port, and :user search
535parameters."
e45de620
TZ
536 (let ((entry (if (stringp entry)
537 nil
538 entry))
539 val)
b8e0f0cd
G
540 (when (setq val (plist-get entry :host))
541 (oset backend host val))
542 (when (setq val (plist-get entry :user))
543 (oset backend user val))
35123c04
TZ
544 (when (setq val (plist-get entry :port))
545 (oset backend port val)))
b8e0f0cd
G
546 backend)
547
548;; (mapcar 'auth-source-backend-parse auth-sources)
549
550(defun* auth-source-search (&rest spec
35123c04 551 &key type max host user port secret
733afdf4 552 require create delete
b8e0f0cd
G
553 &allow-other-keys)
554 "Search or modify authentication backends according to SPEC.
555
556This function parses `auth-sources' for matches of the SPEC
557plist. It can optionally create or update an authentication
558token if requested. A token is just a standard Emacs property
559list with a :secret property that can be a function; all the
560other properties will always hold scalar values.
561
562Typically the :secret property, if present, contains a password.
563
35123c04 564Common search keys are :max, :host, :port, and :user. In
b8e0f0cd
G
565addition, :create specifies how tokens will be or created.
566Finally, :type can specify which backend types you want to check.
567
568A string value is always matched literally. A symbol is matched
569as its string value, literally. All the SPEC values can be
570single values (symbol or string) or lists thereof (in which case
571any of the search terms matches).
572
573:create t means to create a token if possible.
574
575A new token will be created if no matching tokens were found.
576The new token will have only the keys the backend requires. For
577the netrc backend, for instance, that's the user, host, and
35123c04 578port keys.
b8e0f0cd
G
579
580Here's an example:
581
582\(let ((auth-source-creation-defaults '((user . \"defaultUser\")
583 (A . \"default A\"))))
584 (auth-source-search :host \"mine\" :type 'netrc :max 1
585 :P \"pppp\" :Q \"qqqq\"
586 :create t))
587
588which says:
589
590\"Search for any entry matching host 'mine' in backends of type
591 'netrc', maximum one result.
592
593 Create a new entry if you found none. The netrc backend will
35123c04 594 automatically require host, user, and port. The host will be
b8e0f0cd 595 'mine'. We prompt for the user with default 'defaultUser' and
35123c04 596 for the port without a default. We will not prompt for A, Q,
b8e0f0cd 597 or P. The resulting token will only have keys user, host, and
35123c04 598 port.\"
b8e0f0cd
G
599
600:create '(A B C) also means to create a token if possible.
601
602The behavior is like :create t but if the list contains any
603parameter, that parameter will be required in the resulting
604token. The value for that parameter will be obtained from the
605search parameters or from user input. If any queries are needed,
606the alist `auth-source-creation-defaults' will be checked for the
003522ce
G
607default value. If the user, host, or port are missing, the alist
608`auth-source-creation-prompts' will be used to look up the
609prompts IN THAT ORDER (so the 'user prompt will be queried first,
610then 'host, then 'port, and finally 'secret). Each prompt string
611can use %u, %h, and %p to show the user, host, and port.
b8e0f0cd
G
612
613Here's an example:
614
615\(let ((auth-source-creation-defaults '((user . \"defaultUser\")
003522ce
G
616 (A . \"default A\")))
617 (auth-source-creation-prompts
618 '((password . \"Enter IMAP password for %h:%p: \"))))
b8e0f0cd
G
619 (auth-source-search :host '(\"nonesuch\" \"twosuch\") :type 'netrc :max 1
620 :P \"pppp\" :Q \"qqqq\"
621 :create '(A B Q)))
622
623which says:
624
625\"Search for any entry matching host 'nonesuch'
626 or 'twosuch' in backends of type 'netrc', maximum one result.
627
628 Create a new entry if you found none. The netrc backend will
35123c04 629 automatically require host, user, and port. The host will be
003522ce
G
630 'nonesuch' and Q will be 'qqqq'. We prompt for the password
631 with the shown prompt. We will not prompt for Q. The resulting
632 token will have keys user, host, port, A, B, and Q. It will not
633 have P with any value, even though P is used in the search to
634 find only entries that have P set to 'pppp'.\"
b8e0f0cd
G
635
636When multiple values are specified in the search parameter, the
7ba93e94
G
637user is prompted for which one. So :host (X Y Z) would ask the
638user to choose between X, Y, and Z.
b8e0f0cd
G
639
640This creation can fail if the search was not specific enough to
641create a new token (it's up to the backend to decide that). You
642should `catch' the backend-specific error as usual. Some
643backends (netrc, at least) will prompt the user rather than throw
644an error.
645
733afdf4
TZ
646:require (A B C) means that only results that contain those
647tokens will be returned. Thus for instance requiring :secret
648will ensure that any results will actually have a :secret
649property.
650
b8e0f0cd
G
651:delete t means to delete any found entries. nil by default.
652Use `auth-source-delete' in ELisp code instead of calling
653`auth-source-search' directly with this parameter.
654
655:type (X Y Z) will check only those backend types. 'netrc and
656'secrets are the only ones supported right now.
657
658:max N means to try to return at most N items (defaults to 1).
659When 0 the function will return just t or nil to indicate if any
660matches were found. More than N items may be returned, depending
661on the search and the backend.
662
663:host (X Y Z) means to match only hosts X, Y, or Z according to
664the match rules above. Defaults to t.
665
666:user (X Y Z) means to match only users X, Y, or Z according to
667the match rules above. Defaults to t.
668
35123c04 669:port (P Q R) means to match only protocols P, Q, or R.
b8e0f0cd
G
670Defaults to t.
671
672:K (V1 V2 V3) for any other key K will match values V1, V2, or
673V3 (note the match rules above).
674
675The return value is a list with at most :max tokens. Each token
35123c04 676is a plist with keys :backend :host :port :user, plus any other
b8e0f0cd
G
677keys provided by the backend (notably :secret). But note the
678exception for :max 0, which see above.
679
733afdf4
TZ
680The token can hold a :save-function key. If you call that, the
681user will be prompted to save the data to the backend. You can't
682request that this should happen right after creation, because
683`auth-source-search' has no way of knowing if the token is
684actually useful. So the caller must arrange to call this function.
685
b8e0f0cd
G
686The token's :secret key can hold a function. In that case you
687must call it to obtain the actual value."
688 (let* ((backends (mapcar 'auth-source-backend-parse auth-sources))
689 (max (or max 1))
733afdf4 690 (ignored-keys '(:require :create :delete :max))
b8e0f0cd
G
691 (keys (loop for i below (length spec) by 2
692 unless (memq (nth i spec) ignored-keys)
693 collect (nth i spec)))
61e9662e
TZ
694 (cached (auth-source-remembered-p spec))
695 ;; note that we may have cached results but found is still nil
696 ;; (there were no results from the search)
b8e0f0cd 697 (found (auth-source-recall spec))
4a3988d5 698 filtered-backends accessor-key backend)
b8e0f0cd 699
61e9662e 700 (if (and cached auth-source-do-cache)
b8e0f0cd
G
701 (auth-source-do-debug
702 "auth-source-search: found %d CACHED results matching %S"
703 (length found) spec)
704
705 (assert
706 (or (eq t create) (listp create)) t
4a3988d5 707 "Invalid auth-source :create parameter (must be t or a list): %s %s")
b8e0f0cd 708
733afdf4
TZ
709 (assert
710 (listp require) t
711 "Invalid auth-source :require parameter (must be a list): %s")
712
6ce6c742 713 (setq filtered-backends (copy-sequence backends))
b8e0f0cd
G
714 (dolist (backend backends)
715 (dolist (key keys)
716 ;; ignore invalid slots
717 (condition-case signal
718 (unless (eval `(auth-source-search-collection
719 (plist-get spec key)
720 (oref backend ,key)))
721 (setq filtered-backends (delq backend filtered-backends))
722 (return))
723 (invalid-slot-name))))
724
4a3988d5 725 (auth-source-do-trivia
b8e0f0cd
G
726 "auth-source-search: found %d backends matching %S"
727 (length filtered-backends) spec)
728
729 ;; (debug spec "filtered" filtered-backends)
1d2c4a49
LI
730 ;; First go through all the backends without :create, so we can
731 ;; query them all.
4a3988d5
G
732 (setq found (auth-source-search-backends filtered-backends
733 spec
734 ;; to exit early
735 max
733afdf4
TZ
736 ;; create is always nil here
737 nil delete
738 require))
4a3988d5
G
739
740 (auth-source-do-debug
741 "auth-source-search: found %d results (max %d) matching %S"
742 (length found) max spec)
743
1d2c4a49
LI
744 ;; If we didn't find anything, then we allow the backend(s) to
745 ;; create the entries.
38046520 746 (when (and create
4a3988d5
G
747 (not found))
748 (setq found (auth-source-search-backends filtered-backends
749 spec
750 ;; to exit early
751 max
733afdf4
TZ
752 create delete
753 require))
754 (auth-source-do-debug
4a3988d5
G
755 "auth-source-search: CREATED %d results (max %d) matching %S"
756 (length found) max spec))
757
61e9662e
TZ
758 ;; note we remember the lack of result too, if it's applicable
759 (when auth-source-do-cache
4a3988d5
G
760 (auth-source-remember spec found)))
761
e9cb4479 762 found))
4a3988d5 763
733afdf4 764(defun auth-source-search-backends (backends spec max create delete require)
4a3988d5
G
765 (let (matches)
766 (dolist (backend backends)
767 (when (> max (length matches)) ; when we need more matches...
733afdf4
TZ
768 (let* ((bmatches (apply
769 (slot-value backend 'search-function)
770 :backend backend
d7fcec5d 771 :type (slot-value backend :type)
733afdf4
TZ
772 ;; note we're overriding whatever the spec
773 ;; has for :require, :create, and :delete
774 :require require
775 :create create
776 :delete delete
777 spec)))
4a3988d5
G
778 (when bmatches
779 (auth-source-do-trivia
780 "auth-source-search-backend: got %d (max %d) in %s:%s matching %S"
781 (length bmatches) max
782 (slot-value backend :type)
783 (slot-value backend :source)
784 spec)
785 (setq matches (append matches bmatches))))))
786 matches))
b8e0f0cd 787
cbffd0bd
SM
788;; (auth-source-search :max 1)
789;; (funcall (plist-get (nth 0 (auth-source-search :max 1)) :secret))
790;; (auth-source-search :host "nonesuch" :type 'netrc :K 1)
791;; (auth-source-search :host "nonesuch" :type 'secrets)
b8e0f0cd
G
792
793(defun* auth-source-delete (&rest spec
794 &key delete
795 &allow-other-keys)
796 "Delete entries from the authentication backends according to SPEC.
797Calls `auth-source-search' with the :delete property in SPEC set to t.
798The backend may not actually delete the entries.
799
800Returns the deleted entries."
801 (auth-source-search (plist-put spec :delete t)))
802
803(defun auth-source-search-collection (collection value)
2809512e 804 "Returns t is VALUE is t or COLLECTION is t or COLLECTION contains VALUE."
b8e0f0cd
G
805 (when (and (atom collection) (not (eq t collection)))
806 (setq collection (list collection)))
807
808 ;; (debug :collection collection :value value)
809 (or (eq collection t)
810 (eq value t)
811 (equal collection value)
812 (member value collection)))
ed778fad 813
74e8193b
KY
814(defvar auth-source-netrc-cache nil)
815
3b36c17e 816(defun auth-source-forget-all-cached ()
b8e0f0cd 817 "Forget all cached auth-source data."
3b36c17e 818 (interactive)
b8e0f0cd
G
819 (loop for sym being the symbols of password-data
820 ;; when the symbol name starts with auth-source-magic
821 when (string-match (concat "^" auth-source-magic)
822 (symbol-name sym))
823 ;; remove that key
ddb7ffee
LMI
824 do (password-cache-remove (symbol-name sym)))
825 (setq auth-source-netrc-cache nil))
b8e0f0cd 826
cf499a1a
JD
827(defun auth-source-format-cache-entry (spec)
828 "Format SPEC entry to put it in the password cache."
829 (concat auth-source-magic (format "%S" spec)))
830
b8e0f0cd
G
831(defun auth-source-remember (spec found)
832 "Remember FOUND search results for SPEC."
584c9d3f
G
833 (let ((password-cache-expiry auth-source-cache-expiry))
834 (password-cache-add
cf499a1a 835 (auth-source-format-cache-entry spec) found)))
b8e0f0cd
G
836
837(defun auth-source-recall (spec)
838 "Recall FOUND search results for SPEC."
cf499a1a 839 (password-read-from-cache (auth-source-format-cache-entry spec)))
b8e0f0cd 840
61e9662e
TZ
841(defun auth-source-remembered-p (spec)
842 "Check if SPEC is remembered."
843 (password-in-cache-p
cf499a1a 844 (auth-source-format-cache-entry spec)))
61e9662e 845
b8e0f0cd
G
846(defun auth-source-forget (spec)
847 "Forget any cached data matching SPEC exactly.
848
849This is the same SPEC you passed to `auth-source-search'.
850Returns t or nil for forgotten or not found."
cf499a1a 851 (password-cache-remove (auth-source-format-cache-entry spec)))
b8e0f0cd 852
cbffd0bd 853;; (loop for sym being the symbols of password-data when (string-match (concat "^" auth-source-magic) (symbol-name sym)) collect (symbol-name sym))
b8e0f0cd 854
cbffd0bd
SM
855;; (auth-source-remember '(:host "wedd") '(4 5 6))
856;; (auth-source-remembered-p '(:host "wedd"))
857;; (auth-source-remember '(:host "xedd") '(1 2 3))
858;; (auth-source-remembered-p '(:host "xedd"))
859;; (auth-source-remembered-p '(:host "zedd"))
860;; (auth-source-recall '(:host "xedd"))
861;; (auth-source-recall '(:host t))
862;; (auth-source-forget+ :host t)
b8e0f0cd
G
863
864(defun* auth-source-forget+ (&rest spec &allow-other-keys)
865 "Forget any cached data matching SPEC. Returns forgotten count.
866
867This is not a full `auth-source-search' spec but works similarly.
868For instance, \(:host \"myhost\" \"yourhost\") would find all the
869cached data that was found with a search for those two hosts,
870while \(:host t) would find all host entries."
871 (let ((count 0)
872 sname)
873 (loop for sym being the symbols of password-data
874 ;; when the symbol name matches with auth-source-magic
875 when (and (setq sname (symbol-name sym))
876 (string-match (concat "^" auth-source-magic "\\(.+\\)")
877 sname)
878 ;; and the spec matches what was stored in the cache
879 (auth-source-specmatchp spec (read (match-string 1 sname))))
880 ;; remove that key
881 do (progn
882 (password-cache-remove sname)
883 (incf count)))
884 count))
885
886(defun auth-source-specmatchp (spec stored)
887 (let ((keys (loop for i below (length spec) by 2
e9cb4479 888 collect (nth i spec))))
b8e0f0cd
G
889 (not (eq
890 (dolist (key keys)
891 (unless (auth-source-search-collection (plist-get stored key)
892 (plist-get spec key))
893 (return 'no)))
894 'no))))
895
cbffd0bd
SM
896;; (auth-source-pick-first-password :host "z.lifelogs.com")
897;; (auth-source-pick-first-password :port "imap")
f3b54b0e
TZ
898(defun auth-source-pick-first-password (&rest spec)
899 "Pick the first secret found from applying SPEC to `auth-source-search'."
900 (let* ((result (nth 0 (apply 'auth-source-search (plist-put spec :max 1))))
901 (secret (plist-get result :secret)))
902
903 (if (functionp secret)
904 (funcall secret)
905 secret)))
906
907;; (auth-source-format-prompt "test %u %h %p" '((?u "user") (?h "host")))
908(defun auth-source-format-prompt (prompt alist)
909 "Format PROMPT using %x (for any character x) specifiers in ALIST."
910 (dolist (cell alist)
911 (let ((c (nth 0 cell))
912 (v (nth 1 cell)))
913 (when (and c v)
4248cca2
TZ
914 (setq prompt (replace-regexp-in-string (format "%%%c" c)
915 (format "%s" v)
17d14f7e 916 prompt nil t)))))
f3b54b0e 917 prompt)
b8e0f0cd 918
8e22bee0
G
919(defun auth-source-ensure-strings (values)
920 (unless (listp values)
921 (setq values (list values)))
922 (mapcar (lambda (value)
e9cb4479
DU
923 (if (numberp value)
924 (format "%s" value)
925 value))
926 values))
8e22bee0 927
f3b54b0e
TZ
928;;; Backend specific parsing: netrc/authinfo backend
929
8b6c19f4
SM
930(defun auth-source--aput-1 (alist key val)
931 (let ((seen ())
932 (rest alist))
933 (while (and (consp rest) (not (equal key (caar rest))))
934 (push (pop rest) seen))
935 (cons (cons key val)
936 (if (null rest) alist
937 (nconc (nreverse seen)
938 (if (equal key (caar rest)) (cdr rest) rest))))))
939(defmacro auth-source--aput (var key val)
940 `(setq ,var (auth-source--aput-1 ,var ,key ,val)))
941
942(defun auth-source--aget (alist key)
943 (cdr (assoc key alist)))
944
2809512e 945;; (auth-source-netrc-parse :file "~/.authinfo.gpg")
b8e0f0cd
G
946(defun* auth-source-netrc-parse (&rest
947 spec
733afdf4 948 &key file max host user port delete require
b8e0f0cd
G
949 &allow-other-keys)
950 "Parse FILE and return a list of all entries in the file.
951Note that the MAX parameter is used so we can exit the parse early."
952 (if (listp file)
953 ;; We got already parsed contents; just return it.
954 file
955 (when (file-exists-p file)
8e22bee0 956 (setq port (auth-source-ensure-strings port))
b8e0f0cd 957 (with-temp-buffer
2809512e 958 (let* ((max (or max 5000)) ; sanity check: default to stop at 5K
4a3988d5
G
959 (modified 0)
960 (cached (cdr-safe (assoc file auth-source-netrc-cache)))
961 (cached-mtime (plist-get cached :mtime))
962 (cached-secrets (plist-get cached :secret))
2809512e
TZ
963 (check (lambda(alist)
964 (and alist
965 (auth-source-search-collection
966 host
967 (or
968 (auth-source--aget alist "machine")
969 (auth-source--aget alist "host")
970 t))
971 (auth-source-search-collection
972 user
973 (or
974 (auth-source--aget alist "login")
975 (auth-source--aget alist "account")
976 (auth-source--aget alist "user")
977 t))
978 (auth-source-search-collection
979 port
980 (or
981 (auth-source--aget alist "port")
982 (auth-source--aget alist "protocol")
983 t))
984 (or
985 ;; the required list of keys is nil, or
986 (null require)
987 ;; every element of require is in n(ormalized)
988 (let ((n (nth 0 (auth-source-netrc-normalize
989 (list alist) file))))
990 (loop for req in require
991 always (plist-get n req)))))))
992 result)
4a3988d5
G
993
994 (if (and (functionp cached-secrets)
995 (equal cached-mtime
996 (nth 5 (file-attributes file))))
997 (progn
998 (auth-source-do-trivia
999 "auth-source-netrc-parse: using CACHED file data for %s"
1000 file)
1001 (insert (funcall cached-secrets)))
1002 (insert-file-contents file)
1003 ;; cache all netrc files (used to be just .gpg files)
1004 ;; Store the contents of the file heavily encrypted in memory.
1005 ;; (note for the irony-impaired: they are just obfuscated)
8b6c19f4
SM
1006 (auth-source--aput
1007 auth-source-netrc-cache file
1008 (list :mtime (nth 5 (file-attributes file))
1009 :secret (lexical-let ((v (mapcar '1+ (buffer-string))))
1010 (lambda () (apply 'string (mapcar '1- v)))))))
b8e0f0cd 1011 (goto-char (point-min))
2809512e
TZ
1012 (let ((entries (auth-source-netrc-parse-entries check max))
1013 alist)
1014 (while (setq alist (pop entries))
1015 (push (nreverse alist) result)))
b8e0f0cd
G
1016
1017 (when (< 0 modified)
1018 (when auth-source-gpg-encrypt-to
1019 ;; (see bug#7487) making `epa-file-encrypt-to' local to
1020 ;; this buffer lets epa-file skip the key selection query
1021 ;; (see the `local-variable-p' check in
1022 ;; `epa-file-write-region').
1023 (unless (local-variable-p 'epa-file-encrypt-to (current-buffer))
1024 (make-local-variable 'epa-file-encrypt-to))
1025 (if (listp auth-source-gpg-encrypt-to)
1026 (setq epa-file-encrypt-to auth-source-gpg-encrypt-to)))
1027
1028 ;; ask AFTER we've successfully opened the file
733afdf4 1029 (when (y-or-n-p (format "Save file %s? (%d deletions)"
b8e0f0cd
G
1030 file modified))
1031 (write-region (point-min) (point-max) file nil 'silent)
1032 (auth-source-do-debug
1033 "auth-source-netrc-parse: modified %d lines in %s"
1034 modified file)))
1035
1036 (nreverse result))))))
1037
2809512e
TZ
1038(defun auth-source-netrc-parse-next-interesting ()
1039 "Advance to the next interesting position in the current buffer."
1040 ;; If we're looking at a comment or are at the end of the line, move forward
1041 (while (or (looking-at "#")
1042 (and (eolp)
1043 (not (eobp))))
1044 (forward-line 1))
1045 (skip-chars-forward "\t "))
1046
1047(defun auth-source-netrc-parse-one ()
1048 "Read one thing from the current buffer."
1049 (auth-source-netrc-parse-next-interesting)
1050
fa7f427c
DK
1051 (when (or (looking-at "'\\([^']*\\)'")
1052 (looking-at "\"\\([^\"]*\\)\"")
2809512e
TZ
1053 (looking-at "\\([^ \t\n]+\\)"))
1054 (forward-char (length (match-string 0)))
1055 (auth-source-netrc-parse-next-interesting)
1056 (match-string-no-properties 1)))
1057
cc52b6cc
TZ
1058;; with thanks to org-mode
1059(defsubst auth-source-current-line (&optional pos)
1060 (save-excursion
1061 (and pos (goto-char pos))
1062 ;; works also in narrowed buffer, because we start at 1, not point-min
1063 (+ (if (bolp) 1 0) (count-lines 1 (point)))))
1064
2809512e
TZ
1065(defun auth-source-netrc-parse-entries(check max)
1066 "Parse up to MAX netrc entries, passed by CHECK, from the current buffer."
1067 (let ((adder (lambda(check alist all)
1068 (when (and
1069 alist
1070 (> max (length all))
1071 (funcall check alist))
1072 (push alist all))
1073 all))
1074 item item2 all alist default)
1075 (while (setq item (auth-source-netrc-parse-one))
1076 (setq default (equal item "default"))
1077 ;; We're starting a new machine. Save the old one.
1078 (when (and alist
1079 (or default
1080 (equal item "machine")))
924d6997
G
1081 ;; (auth-source-do-trivia
1082 ;; "auth-source-netrc-parse-entries: got entry %S" alist)
2809512e
TZ
1083 (setq all (funcall adder check alist all)
1084 alist nil))
1085 ;; In default entries, we don't have a next token.
1086 ;; We store them as ("machine" . t)
1087 (if default
1088 (push (cons "machine" t) alist)
1089 ;; Not a default entry. Grab the next item.
1090 (when (setq item2 (auth-source-netrc-parse-one))
cc52b6cc
TZ
1091 ;; Did we get a "machine" value?
1092 (if (equal item2 "machine")
1093 (progn
1094 (gnus-error 1
1095 "%s: Unexpected 'machine' token at line %d"
1096 "auth-source-netrc-parse-entries"
1097 (auth-source-current-line))
1098 (forward-line 1))
1099 (push (cons item item2) alist)))))
2809512e
TZ
1100
1101 ;; Clean up: if there's an entry left over, use it.
1102 (when alist
cc52b6cc 1103 (setq all (funcall adder check alist all))
924d6997
G
1104 ;; (auth-source-do-trivia
1105 ;; "auth-source-netrc-parse-entries: got2 entry %S" alist)
1106 )
2809512e
TZ
1107 (nreverse all)))
1108
936d08bb
G
1109(defvar auth-source-passphrase-alist nil)
1110
936d08bb 1111(defun auth-source-token-passphrase-callback-function (context key-id file)
7f6d634a
DU
1112 (let* ((file (file-truename file))
1113 (entry (assoc file auth-source-passphrase-alist))
1114 passphrase)
1115 ;; return the saved passphrase, calling a function if needed
1116 (or (copy-sequence (if (functionp (cdr entry))
1117 (funcall (cdr entry))
1118 (cdr entry)))
1119 (progn
1120 (unless entry
1121 (setq entry (list file))
1122 (push entry auth-source-passphrase-alist))
1123 (setq passphrase
1124 (read-passwd
1125 (format "Passphrase for %s tokens: " file)
1126 t))
1127 (setcdr entry (lexical-let ((p (copy-sequence passphrase)))
1128 (lambda () p)))
1129 passphrase))))
936d08bb
G
1130
1131;; (auth-source-epa-extract-gpg-token "gpg:LS0tLS1CRUdJTiBQR1AgTUVTU0FHRS0tLS0tClZlcnNpb246IEdudVBHIHYxLjQuMTEgKEdOVS9MaW51eCkKCmpBMEVBd01DT25qMjB1ak9rZnRneVI3K21iNm9aZWhuLzRad3cySkdlbnVaKzRpeEswWDY5di9icDI1U1dsQT0KPS9yc2wKLS0tLS1FTkQgUEdQIE1FU1NBR0UtLS0tLQo=" "~/.netrc")
1132(defun auth-source-epa-extract-gpg-token (secret file)
1133 "Pass either the decoded SECRET or the gpg:BASE64DATA version.
1134FILE is the file from which we obtained this token."
1135 (when (string-match "^gpg:\\(.+\\)" secret)
1136 (setq secret (base64-decode-string (match-string 1 secret))))
1137 (let ((context (epg-make-context 'OpenPGP))
1138 plain)
1139 (epg-context-set-passphrase-callback
1140 context
1141 (cons #'auth-source-token-passphrase-callback-function
1142 file))
1143 (epg-decrypt-string context secret)))
1144
1145;; (insert (auth-source-epa-make-gpg-token "mysecret" "~/.netrc"))
2b8c5660 1146(defun auth-source-epa-make-gpg-token (secret file)
936d08bb
G
1147 (let ((context (epg-make-context 'OpenPGP))
1148 (pp-escape-newlines nil)
1149 cipher)
1150 (epg-context-set-armor context t)
1151 (epg-context-set-passphrase-callback
1152 context
1153 (cons #'auth-source-token-passphrase-callback-function
1154 file))
1155 (setq cipher (epg-encrypt-string context secret nil))
1156 (with-temp-buffer
1157 (insert cipher)
1158 (base64-encode-region (point-min) (point-max) t)
1159 (concat "gpg:" (buffer-substring-no-properties
1160 (point-min)
1161 (point-max))))))
2b8c5660
TZ
1162
1163(defun auth-source-netrc-normalize (alist filename)
b8e0f0cd
G
1164 (mapcar (lambda (entry)
1165 (let (ret item)
1166 (while (setq item (pop entry))
1167 (let ((k (car item))
1168 (v (cdr item)))
1169
1170 ;; apply key aliases
1171 (setq k (cond ((member k '("machine")) "host")
1172 ((member k '("login" "account")) "user")
1173 ((member k '("protocol")) "port")
1174 ((member k '("password")) "secret")
1175 (t k)))
1176
1177 ;; send back the secret in a function (lexical binding)
1178 (when (equal k "secret")
936d08bb
G
1179 (setq v (lexical-let ((lexv v)
1180 (token-decoder nil))
1181 (when (string-match "^gpg:" lexv)
1182 ;; it's a GPG token: create a token decoder
1183 ;; which unsets itself once
1184 (setq token-decoder
1185 (lambda (val)
1186 (prog1
1187 (auth-source-epa-extract-gpg-token
1188 val
1189 filename)
1190 (setq token-decoder nil)))))
1191 (lambda ()
1192 (when token-decoder
1193 (setq lexv (funcall token-decoder lexv)))
1194 lexv))))
e9cb4479
DU
1195 (setq ret (plist-put ret
1196 (intern (concat ":" k))
1197 v))))
1198 ret))
1199 alist))
b8e0f0cd 1200
cbffd0bd
SM
1201;; (setq secret (plist-get (nth 0 (auth-source-search :host t :type 'netrc :K 1 :max 1)) :secret))
1202;; (funcall secret)
b8e0f0cd
G
1203
1204(defun* auth-source-netrc-search (&rest
1205 spec
733afdf4 1206 &key backend require create delete
35123c04 1207 type max host user port
b8e0f0cd 1208 &allow-other-keys)
e9cb4479 1209 "Given a property list SPEC, return search matches from the :backend.
b8e0f0cd
G
1210See `auth-source-search' for details on SPEC."
1211 ;; just in case, check that the type is correct (null or same as the backend)
1212 (assert (or (null type) (eq type (oref backend type)))
d5e9a4e9 1213 t "Invalid netrc search: %s %s")
b8e0f0cd
G
1214
1215 (let ((results (auth-source-netrc-normalize
1216 (auth-source-netrc-parse
1217 :max max
733afdf4 1218 :require require
b8e0f0cd
G
1219 :delete delete
1220 :file (oref backend source)
1221 :host (or host t)
1222 :user (or user t)
2b8c5660
TZ
1223 :port (or port t))
1224 (oref backend source))))
b8e0f0cd
G
1225
1226 ;; if we need to create an entry AND none were found to match
1227 (when (and create
4a3988d5 1228 (not results))
b8e0f0cd 1229
584c9d3f
G
1230 ;; create based on the spec and record the value
1231 (setq results (or
1232 ;; if the user did not want to create the entry
1233 ;; in the file, it will be returned
1234 (apply (slot-value backend 'create-function) spec)
1235 ;; if not, we do the search again without :create
1236 ;; to get the updated data.
1237
1238 ;; the result will be returned, even if the search fails
1239 (apply 'auth-source-netrc-search
1240 (plist-put spec :create nil)))))
b8e0f0cd
G
1241 results))
1242
fa41748c
G
1243(defun auth-source-netrc-element-or-first (v)
1244 (if (listp v)
1245 (nth 0 v)
1246 v))
1247
cbffd0bd
SM
1248;; (auth-source-search :host "nonesuch" :type 'netrc :max 1 :create t)
1249;; (auth-source-search :host "nonesuch" :type 'netrc :max 1 :create t :create-extra-keys '((A "default A") (B)))
b8e0f0cd
G
1250
1251(defun* auth-source-netrc-create (&rest spec
1252 &key backend
35123c04 1253 secret host user port create
b8e0f0cd 1254 &allow-other-keys)
35123c04 1255 (let* ((base-required '(host user port secret))
b8e0f0cd
G
1256 ;; we know (because of an assertion in auth-source-search) that the
1257 ;; :create parameter is either t or a list (which includes nil)
1258 (create-extra (if (eq t create) nil create))
e9cb4479
DU
1259 (current-data (car (auth-source-search :max 1
1260 :host host
1261 :port port)))
b8e0f0cd
G
1262 (required (append base-required create-extra))
1263 (file (oref backend source))
1264 (add "")
1265 ;; `valist' is an alist
584c9d3f
G
1266 valist
1267 ;; `artificial' will be returned if no creation is needed
1268 artificial)
b8e0f0cd
G
1269
1270 ;; only for base required elements (defined as function parameters):
1271 ;; fill in the valist with whatever data we may have from the search
7ba93e94 1272 ;; we complete the first value if it's a list and use the value otherwise
b8e0f0cd
G
1273 (dolist (br base-required)
1274 (when (symbol-value br)
7ba93e94
G
1275 (let ((br-choice (cond
1276 ;; all-accepting choice (predicate is t)
1277 ((eq t (symbol-value br)) nil)
1278 ;; just the value otherwise
1279 (t (symbol-value br)))))
1280 (when br-choice
8b6c19f4 1281 (auth-source--aput valist br br-choice)))))
b8e0f0cd
G
1282
1283 ;; for extra required elements, see if the spec includes a value for them
1284 (dolist (er create-extra)
1285 (let ((name (concat ":" (symbol-name er)))
1286 (keys (loop for i below (length spec) by 2
1287 collect (nth i spec))))
1288 (dolist (k keys)
1289 (when (equal (symbol-name k) name)
8b6c19f4 1290 (auth-source--aput valist er (plist-get spec k))))))
b8e0f0cd
G
1291
1292 ;; for each required element
1293 (dolist (r required)
8b6c19f4 1294 (let* ((data (auth-source--aget valist r))
4a3988d5 1295 ;; take the first element if the data is a list
ddb7ffee 1296 (data (or (auth-source-netrc-element-or-first data)
e9cb4479
DU
1297 (plist-get current-data
1298 (intern (format ":%s" r) obarray))))
4a3988d5 1299 ;; this is the default to be offered
8b6c19f4
SM
1300 (given-default (auth-source--aget
1301 auth-source-creation-defaults r))
733afdf4
TZ
1302 ;; the default supplementals are simple:
1303 ;; for the user, try `given-default' and then (user-login-name);
1304 ;; otherwise take `given-default'
b8e0f0cd 1305 (default (cond
733afdf4
TZ
1306 ((and (not given-default) (eq r 'user))
1307 (user-login-name))
003522ce
G
1308 (t given-default)))
1309 (printable-defaults (list
1310 (cons 'user
1311 (or
1312 (auth-source-netrc-element-or-first
8b6c19f4 1313 (auth-source--aget valist 'user))
003522ce
G
1314 (plist-get artificial :user)
1315 "[any user]"))
1316 (cons 'host
1317 (or
1318 (auth-source-netrc-element-or-first
8b6c19f4 1319 (auth-source--aget valist 'host))
003522ce
G
1320 (plist-get artificial :host)
1321 "[any host]"))
1322 (cons 'port
1323 (or
1324 (auth-source-netrc-element-or-first
8b6c19f4 1325 (auth-source--aget valist 'port))
003522ce
G
1326 (plist-get artificial :port)
1327 "[any port]"))))
8b6c19f4 1328 (prompt (or (auth-source--aget auth-source-creation-prompts r)
003522ce 1329 (case r
733afdf4
TZ
1330 (secret "%p password for %u@%h: ")
1331 (user "%p user name for %h: ")
1332 (host "%p host name for user %u: ")
1333 (port "%p port for %u@%h: "))
003522ce
G
1334 (format "Enter %s (%%u@%%h:%%p): " r)))
1335 (prompt (auth-source-format-prompt
1336 prompt
8b6c19f4
SM
1337 `((?u ,(auth-source--aget printable-defaults 'user))
1338 (?h ,(auth-source--aget printable-defaults 'host))
1339 (?p ,(auth-source--aget printable-defaults 'port))))))
4a3988d5 1340
aa2ebce9 1341 ;; Store the data, prompting for the password if needed.
5c7f66a0
G
1342 (setq data (or data
1343 (if (eq r 'secret)
1344 ;; Special case prompt for passwords.
1345 ;; TODO: make the default (setq auth-source-netrc-use-gpg-tokens `((,(if (boundp 'epa-file-auto-mode-alist-entry) (car (symbol-value 'epa-file-auto-mode-alist-entry)) "\\.gpg\\'") nil) (t gpg)))
1346 ;; TODO: or maybe leave as (setq auth-source-netrc-use-gpg-tokens 'never)
1347 (let* ((ep (format "Use GPG password tokens in %s?" file))
1348 (gpg-encrypt
1349 (cond
1350 ((eq auth-source-netrc-use-gpg-tokens 'never)
1351 'never)
1352 ((listp auth-source-netrc-use-gpg-tokens)
1353 (let ((check (copy-sequence
1354 auth-source-netrc-use-gpg-tokens))
1355 item ret)
1356 (while check
1357 (setq item (pop check))
1358 (when (or (eq (car item) t)
1359 (string-match (car item) file))
1360 (setq ret (cdr item))
1361 (setq check nil)))))
1362 (t 'never)))
1363 (plain (or (eval default) (read-passwd prompt))))
1364 ;; ask if we don't know what to do (in which case
1365 ;; auth-source-netrc-use-gpg-tokens must be a list)
1366 (unless gpg-encrypt
1367 (setq gpg-encrypt (if (y-or-n-p ep) 'gpg 'never))
1368 ;; TODO: save the defcustom now? or ask?
1369 (setq auth-source-netrc-use-gpg-tokens
1370 (cons `(,file ,gpg-encrypt)
1371 auth-source-netrc-use-gpg-tokens)))
1372 (if (eq gpg-encrypt 'gpg)
1373 (auth-source-epa-make-gpg-token plain file)
1374 plain))
1375 (if (stringp default)
1376 (read-string (if (string-match ": *\\'" prompt)
1377 (concat (substring prompt 0 (match-beginning 0))
1378 " (default " default "): ")
1379 (concat prompt "(default " default ") "))
1380 nil nil default)
1381 (eval default)))))
b8e0f0cd 1382
584c9d3f
G
1383 (when data
1384 (setq artificial (plist-put artificial
1385 (intern (concat ":" (symbol-name r)))
1386 (if (eq r 'secret)
1387 (lexical-let ((data data))
1388 (lambda () data))
1389 data))))
1390
aa2ebce9 1391 ;; When r is not an empty string...
b8e0f0cd
G
1392 (when (and (stringp data)
1393 (< 0 (length data)))
4a3988d5
G
1394 ;; this function is not strictly necessary but I think it
1395 ;; makes the code clearer -tzz
1396 (let ((printer (lambda ()
7ba93e94
G
1397 ;; append the key (the symbol name of r)
1398 ;; and the value in r
6a6e4d93 1399 (format "%s%s %s"
7ba93e94
G
1400 ;; prepend a space
1401 (if (zerop (length add)) "" " ")
1402 ;; remap auth-source tokens to netrc
1403 (case r
0adf5618
SM
1404 (user "login")
1405 (host "machine")
1406 (secret "password")
1407 (port "port") ; redundant but clearer
b8e0f0cd 1408 (t (symbol-name r)))
005a89ff 1409 (if (string-match "[\"# ]" data)
e9cb4479
DU
1410 (format "%S" data)
1411 data)))))
4a3988d5 1412 (setq add (concat add (funcall printer)))))))
b8e0f0cd 1413
733afdf4
TZ
1414 (plist-put
1415 artificial
1416 :save-function
1417 (lexical-let ((file file)
1418 (add add))
1419 (lambda () (auth-source-netrc-saver file add))))
1420
1421 (list artificial)))
1422
4248cca2 1423;;(funcall (plist-get (nth 0 (auth-source-search :host '("nonesuch2") :user "tzz" :port "imap" :create t :max 1)) :save-function))
733afdf4
TZ
1424(defun auth-source-netrc-saver (file add)
1425 "Save a line ADD in FILE, prompting along the way.
4248cca2
TZ
1426Respects `auth-source-save-behavior'. Uses
1427`auth-source-netrc-cache' to avoid prompting more than once."
1428 (let* ((key (format "%s %s" file (rfc2104-hash 'md5 64 16 file add)))
1429 (cached (assoc key auth-source-netrc-cache)))
1430
1431 (if cached
1432 (auth-source-do-trivia
1433 "auth-source-netrc-saver: found previous run for key %s, returning"
1434 key)
1435 (with-temp-buffer
1436 (when (file-exists-p file)
1437 (insert-file-contents file))
1438 (when auth-source-gpg-encrypt-to
1439 ;; (see bug#7487) making `epa-file-encrypt-to' local to
1440 ;; this buffer lets epa-file skip the key selection query
1441 ;; (see the `local-variable-p' check in
1442 ;; `epa-file-write-region').
1443 (unless (local-variable-p 'epa-file-encrypt-to (current-buffer))
1444 (make-local-variable 'epa-file-encrypt-to))
1445 (if (listp auth-source-gpg-encrypt-to)
1446 (setq epa-file-encrypt-to auth-source-gpg-encrypt-to)))
1447 ;; we want the new data to be found first, so insert at beginning
1448 (goto-char (point-min))
1449
aa2ebce9 1450 ;; Ask AFTER we've successfully opened the file.
4248cca2
TZ
1451 (let ((prompt (format "Save auth info to file %s? " file))
1452 (done (not (eq auth-source-save-behavior 'ask)))
1453 (bufname "*auth-source Help*")
1454 k)
1455 (while (not done)
1456 (setq k (auth-source-read-char-choice prompt '(?y ?n ?N ?e ??)))
1457 (case k
1458 (?y (setq done t))
1459 (?? (save-excursion
1460 (with-output-to-temp-buffer bufname
1461 (princ
1462 (concat "(y)es, save\n"
1463 "(n)o but use the info\n"
1464 "(N)o and don't ask to save again\n"
1465 "(e)dit the line\n"
1466 "(?) for help as you can see.\n"))
aa2ebce9
SM
1467 ;; Why? Doesn't with-output-to-temp-buffer already do
1468 ;; the exact same thing anyway? --Stef
4248cca2
TZ
1469 (set-buffer standard-output)
1470 (help-mode))))
1471 (?n (setq add ""
1472 done t))
3451795c 1473 (?N
e9cb4479
DU
1474 (setq add ""
1475 done t)
1476 (customize-save-variable 'auth-source-save-behavior nil))
4248cca2
TZ
1477 (?e (setq add (read-string "Line to add: " add)))
1478 (t nil)))
1479
1480 (when (get-buffer-window bufname)
1481 (delete-window (get-buffer-window bufname)))
1482
aa2ebce9 1483 ;; Make sure the info is not saved.
4248cca2
TZ
1484 (when (null auth-source-save-behavior)
1485 (setq add ""))
1486
1487 (when (< 0 (length add))
1488 (progn
1489 (unless (bolp)
1490 (insert "\n"))
1491 (insert add "\n")
1492 (write-region (point-min) (point-max) file nil 'silent)
4dcb0d7a
LMI
1493 ;; Make the .authinfo file non-world-readable.
1494 (set-file-modes file #o600)
4248cca2
TZ
1495 (auth-source-do-debug
1496 "auth-source-netrc-create: wrote 1 new line to %s"
1497 file)
1498 (message "Saved new authentication information to %s" file)
1499 nil))))
8b6c19f4 1500 (auth-source--aput auth-source-netrc-cache key "ran"))))
b8e0f0cd
G
1501
1502;;; Backend specific parsing: Secrets API backend
1503
cbffd0bd
SM
1504;; (let ((auth-sources '(default))) (auth-source-search :max 1 :create t))
1505;; (let ((auth-sources '(default))) (auth-source-search :max 1 :delete t))
1506;; (let ((auth-sources '(default))) (auth-source-search :max 1))
1507;; (let ((auth-sources '(default))) (auth-source-search))
1508;; (let ((auth-sources '("secrets:Login"))) (auth-source-search :max 1))
1509;; (let ((auth-sources '("secrets:Login"))) (auth-source-search :max 1 :signon_realm "https://git.gnus.org/Git"))
b8e0f0cd
G
1510
1511(defun* auth-source-secrets-search (&rest
1512 spec
1513 &key backend create delete label
35123c04 1514 type max host user port
b8e0f0cd
G
1515 &allow-other-keys)
1516 "Search the Secrets API; spec is like `auth-source'.
1517
1518The :label key specifies the item's label. It is the only key
1519that can specify a substring. Any :label value besides a string
1520will allow any label.
1521
1522All other search keys must match exactly. If you need substring
1523matching, do a wider search and narrow it down yourself.
1524
1525You'll get back all the properties of the token as a plist.
1526
5415d076 1527Here's an example that looks for the first item in the 'Login'
b8e0f0cd
G
1528Secrets collection:
1529
5415d076 1530 \(let ((auth-sources '(\"secrets:Login\")))
b8e0f0cd
G
1531 (auth-source-search :max 1)
1532
5415d076 1533Here's another that looks for the first item in the 'Login'
b8e0f0cd
G
1534Secrets collection whose label contains 'gnus':
1535
5415d076 1536 \(let ((auth-sources '(\"secrets:Login\")))
b8e0f0cd
G
1537 (auth-source-search :max 1 :label \"gnus\")
1538
5415d076 1539And this one looks for the first item in the 'Login' Secrets
b8e0f0cd 1540collection that's a Google Chrome entry for the git.gnus.org site
5415d076 1541authentication tokens:
b8e0f0cd 1542
5415d076 1543 \(let ((auth-sources '(\"secrets:Login\")))
b8e0f0cd
G
1544 (auth-source-search :max 1 :signon_realm \"https://git.gnus.org/Git\"))
1545"
1546
1547 ;; TODO
1548 (assert (not create) nil
1549 "The Secrets API auth-source backend doesn't support creation yet")
1550 ;; TODO
1551 ;; (secrets-delete-item coll elt)
1552 (assert (not delete) nil
1553 "The Secrets API auth-source backend doesn't support deletion yet")
1554
1555 (let* ((coll (oref backend source))
1556 (max (or max 5000)) ; sanity check: default to stop at 5K
a3095f42 1557 (ignored-keys '(:create :delete :max :backend :label :require :type))
b8e0f0cd
G
1558 (search-keys (loop for i below (length spec) by 2
1559 unless (memq (nth i spec) ignored-keys)
1560 collect (nth i spec)))
1561 ;; build a search spec without the ignored keys
1562 ;; if a search key is nil or t (match anything), we skip it
5415d076
G
1563 (search-spec (apply 'append (mapcar
1564 (lambda (k)
1565 (if (or (null (plist-get spec k))
1566 (eq t (plist-get spec k)))
1567 nil
1568 (list k (plist-get spec k))))
e9cb4479 1569 search-keys)))
35123c04 1570 ;; needed keys (always including host, login, port, and secret)
d638ac9e 1571 (returned-keys (mm-delete-duplicates (append
e9cb4479
DU
1572 '(:host :login :port :secret)
1573 search-keys)))
b8e0f0cd
G
1574 (items (loop for item in (apply 'secrets-search-items coll search-spec)
1575 unless (and (stringp label)
1576 (not (string-match label item)))
1577 collect item))
1578 ;; TODO: respect max in `secrets-search-items', not after the fact
5415d076 1579 (items (butlast items (- (length items) max)))
b8e0f0cd
G
1580 ;; convert the item name to a full plist
1581 (items (mapcar (lambda (item)
1582 (append
1583 ;; make an entry for the secret (password) element
1584 (list
1585 :secret
1586 (lexical-let ((v (secrets-get-secret coll item)))
1587 (lambda () v)))
1588 ;; rewrite the entry from ((k1 v1) (k2 v2)) to plist
5415d076
G
1589 (apply 'append
1590 (mapcar (lambda (entry)
1591 (list (car entry) (cdr entry)))
1592 (secrets-get-attributes coll item)))))
b8e0f0cd
G
1593 items))
1594 ;; ensure each item has each key in `returned-keys'
1595 (items (mapcar (lambda (plist)
1596 (append
5415d076
G
1597 (apply 'append
1598 (mapcar (lambda (req)
1599 (if (plist-get plist req)
1600 nil
1601 (list req nil)))
1602 returned-keys))
b8e0f0cd
G
1603 plist))
1604 items)))
1605 items))
1606
1607(defun* auth-source-secrets-create (&rest
1608 spec
35123c04 1609 &key backend type max host user port
b8e0f0cd
G
1610 &allow-other-keys)
1611 ;; TODO
1612 ;; (apply 'secrets-create-item (auth-get-source entry) name passwd spec)
1613 (debug spec))
1614
d7fcec5d
TZ
1615;;; Backend specific parsing: Mac OS Keychain (using /usr/bin/security) backend
1616
1617;; (let ((auth-sources '(macos-keychain-internet))) (auth-source-search :max 1 :create t))
1618;; (let ((auth-sources '(macos-keychain-internet))) (auth-source-search :max 1 :delete t))
1619;; (let ((auth-sources '(macos-keychain-internet))) (auth-source-search :max 1))
1620;; (let ((auth-sources '(macos-keychain-internet))) (auth-source-search))
1621
1622;; (let ((auth-sources '(macos-keychain-generic))) (auth-source-search :max 1 :create t))
1623;; (let ((auth-sources '(macos-keychain-generic))) (auth-source-search :max 1 :delete t))
1624;; (let ((auth-sources '(macos-keychain-generic))) (auth-source-search :max 1))
1625;; (let ((auth-sources '(macos-keychain-generic))) (auth-source-search))
1626
1627;; (let ((auth-sources '("macos-keychain-internet:/Users/tzz/Library/Keychains/login.keychain"))) (auth-source-search :max 1))
1628;; (let ((auth-sources '("macos-keychain-generic:Login"))) (auth-source-search :max 1 :host "git.gnus.org"))
1629
1630(defun* auth-source-macos-keychain-search (&rest
1631 spec
1632 &key backend create delete label
1633 type max host user port
1634 &allow-other-keys)
1635 "Search the MacOS Keychain; spec is like `auth-source'.
1636
1637All search keys must match exactly. If you need substring
1638matching, do a wider search and narrow it down yourself.
1639
1640You'll get back all the properties of the token as a plist.
1641
1642The :type key is either 'macos-keychain-internet or
1643'macos-keychain-generic.
1644
1645For the internet keychain type, the :label key searches the
1646item's labels (\"-l LABEL\" passed to \"/usr/bin/security\").
1647Similarly, :host maps to \"-s HOST\", :user maps to \"-a USER\",
1648and :port maps to \"-P PORT\" or \"-r PROT\"
1649(note PROT has to be a 4-character string).
1650
1651For the generic keychain type, the :label key searches the item's
1652labels (\"-l LABEL\" passed to \"/usr/bin/security\").
1653Similarly, :host maps to \"-c HOST\" (the \"creator\" keychain
1654field), :user maps to \"-a USER\", and :port maps to \"-s PORT\".
1655
1656Here's an example that looks for the first item in the default
1657generic MacOS Keychain:
1658
1659 \(let ((auth-sources '(macos-keychain-generic)))
1660 (auth-source-search :max 1)
1661
1662Here's another that looks for the first item in the internet
1663MacOS Keychain collection whose label is 'gnus':
1664
1665 \(let ((auth-sources '(macos-keychain-internet)))
1666 (auth-source-search :max 1 :label \"gnus\")
1667
1668And this one looks for the first item in the internet keychain
1669entries for git.gnus.org:
1670
1671 \(let ((auth-sources '(macos-keychain-internet\")))
1672 (auth-source-search :max 1 :host \"git.gnus.org\"))
1673"
1674 ;; TODO
1675 (assert (not create) nil
1676 "The MacOS Keychain auth-source backend doesn't support creation yet")
1677 ;; TODO
1678 ;; (macos-keychain-delete-item coll elt)
1679 (assert (not delete) nil
1680 "The MacOS Keychain auth-source backend doesn't support deletion yet")
1681
1682 (let* ((coll (oref backend source))
1683 (max (or max 5000)) ; sanity check: default to stop at 5K
1684 (ignored-keys '(:create :delete :max :backend :label))
1685 (search-keys (loop for i below (length spec) by 2
1686 unless (memq (nth i spec) ignored-keys)
1687 collect (nth i spec)))
1688 ;; build a search spec without the ignored keys
1689 ;; if a search key is nil or t (match anything), we skip it
1690 (search-spec (apply 'append (mapcar
1691 (lambda (k)
1692 (if (or (null (plist-get spec k))
1693 (eq t (plist-get spec k)))
1694 nil
1695 (list k (plist-get spec k))))
1696 search-keys)))
1697 ;; needed keys (always including host, login, port, and secret)
1698 (returned-keys (mm-delete-duplicates (append
1699 '(:host :login :port :secret)
1700 search-keys)))
1701 (items (apply 'auth-source-macos-keychain-search-items
1702 coll
1703 type
1704 max
1705 search-spec))
1706
1707 ;; ensure each item has each key in `returned-keys'
1708 (items (mapcar (lambda (plist)
1709 (append
1710 (apply 'append
1711 (mapcar (lambda (req)
1712 (if (plist-get plist req)
1713 nil
1714 (list req nil)))
1715 returned-keys))
1716 plist))
1717 items)))
1718 items))
1719
1720(defun* auth-source-macos-keychain-search-items (coll type max
1721 &rest spec
1722 &key label type
1723 host user port
1724 &allow-other-keys)
1725
1726 (let* ((keychain-generic (eq type 'macos-keychain-generic))
1727 (args `(,(if keychain-generic
1728 "find-generic-password"
1729 "find-internet-password")
1730 "-g"))
1731 (ret (list :type type)))
1732 (when label
1733 (setq args (append args (list "-l" label))))
1734 (when host
1735 (setq args (append args (list (if keychain-generic "-c" "-s") host))))
1736 (when user
1737 (setq args (append args (list "-a" user))))
1738
1739 (when port
1740 (if keychain-generic
1741 (setq args (append args (list "-s" port)))
1742 (setq args (append args (list
1743 (if (string-match "[0-9]+" port) "-P" "-r")
1744 port)))))
1745
1746 (unless (equal coll "default")
1747 (setq args (append args (list coll))))
1748
1749 (with-temp-buffer
1750 (apply 'call-process "/usr/bin/security" nil t nil args)
1751 (goto-char (point-min))
1752 (while (not (eobp))
1753 (cond
1754 ((looking-at "^password: \"\\(.+\\)\"$")
1755 (auth-source-macos-keychain-result-append
1756 ret
1757 keychain-generic
1758 "secret"
1759 (lexical-let ((v (match-string 1)))
1760 (lambda () v))))
1761 ;; TODO: check if this is really the label
1762 ;; match 0x00000007 <blob>="AppleID"
1763 ((looking-at "^[ ]+0x00000007 <blob>=\"\\(.+\\)\"")
1764 (auth-source-macos-keychain-result-append
1765 ret
1766 keychain-generic
1767 "label"
1768 (match-string 1)))
1769 ;; match "crtr"<uint32>="aapl"
1770 ;; match "svce"<blob>="AppleID"
1771 ((looking-at "^[ ]+\"\\([a-z]+\\)\"[^=]+=\"\\(.+\\)\"")
1772 (auth-source-macos-keychain-result-append
1773 ret
1774 keychain-generic
1775 (match-string 1)
1776 (match-string 2))))
1777 (forward-line)))
1778 ;; return `ret' iff it has the :secret key
1779 (and (plist-get ret :secret) (list ret))))
1780
1781(defun auth-source-macos-keychain-result-append (result generic k v)
d6e7c17b 1782 (push v result)
d7fcec5d
TZ
1783 (setq k (cond
1784 ((equal k "acct") "user")
1785 ;; for generic keychains, creator is host, service is port
1786 ((and generic (equal k "crtr")) "host")
1787 ((and generic (equal k "svce")) "port")
1788 ;; for internet keychains, protocol is port, server is host
1789 ((and (not generic) (equal k "ptcl")) "port")
1790 ((and (not generic) (equal k "srvr")) "host")
1791 (t k)))
1792
d6e7c17b 1793 (push (intern (format ":%s" k)) result))
d7fcec5d
TZ
1794
1795(defun* auth-source-macos-keychain-create (&rest
1796 spec
1797 &key backend type max host user port
1798 &allow-other-keys)
1799 ;; TODO
1800 (debug spec))
1801
8977de27
DU
1802;;; Backend specific parsing: PLSTORE backend
1803
1804(defun* auth-source-plstore-search (&rest
1805 spec
1806 &key backend create delete label
1807 type max host user port
1808 &allow-other-keys)
1809 "Search the PLSTORE; spec is like `auth-source'."
b09c3fe0 1810 (let* ((store (oref backend data))
8977de27 1811 (max (or max 5000)) ; sanity check: default to stop at 5K
a3095f42 1812 (ignored-keys '(:create :delete :max :backend :label :require :type))
8977de27
DU
1813 (search-keys (loop for i below (length spec) by 2
1814 unless (memq (nth i spec) ignored-keys)
1815 collect (nth i spec)))
1816 ;; build a search spec without the ignored keys
1817 ;; if a search key is nil or t (match anything), we skip it
1818 (search-spec (apply 'append (mapcar
1819 (lambda (k)
e9cb4479
DU
1820 (let ((v (plist-get spec k)))
1821 (if (or (null v)
1822 (eq t v))
1823 nil
1824 (if (stringp v)
1825 (setq v (list v)))
1826 (list k v))))
1827 search-keys)))
8977de27
DU
1828 ;; needed keys (always including host, login, port, and secret)
1829 (returned-keys (mm-delete-duplicates (append
e9cb4479
DU
1830 '(:host :login :port :secret)
1831 search-keys)))
8977de27 1832 (items (plstore-find store search-spec))
e9cb4479 1833 (item-names (mapcar #'car items))
8977de27
DU
1834 (items (butlast items (- (length items) max)))
1835 ;; convert the item to a full plist
1836 (items (mapcar (lambda (item)
e9cb4479
DU
1837 (let* ((plist (copy-tree (cdr item)))
1838 (secret (plist-member plist :secret)))
1839 (if secret
1840 (setcar
1841 (cdr secret)
1842 (lexical-let ((v (car (cdr secret))))
1843 (lambda () v))))
1844 plist))
8977de27
DU
1845 items))
1846 ;; ensure each item has each key in `returned-keys'
1847 (items (mapcar (lambda (plist)
1848 (append
1849 (apply 'append
1850 (mapcar (lambda (req)
1851 (if (plist-get plist req)
1852 nil
1853 (list req nil)))
1854 returned-keys))
1855 plist))
1856 items)))
f3078a00
DU
1857 (cond
1858 ;; if we need to create an entry AND none were found to match
1859 ((and create
e9cb4479 1860 (not items))
8977de27
DU
1861
1862 ;; create based on the spec and record the value
1863 (setq items (or
e9cb4479
DU
1864 ;; if the user did not want to create the entry
1865 ;; in the file, it will be returned
1866 (apply (slot-value backend 'create-function) spec)
1867 ;; if not, we do the search again without :create
1868 ;; to get the updated data.
1869
1870 ;; the result will be returned, even if the search fails
1871 (apply 'auth-source-plstore-search
1872 (plist-put spec :create nil)))))
f3078a00 1873 ((and delete
e9cb4479 1874 item-names)
f3078a00 1875 (dolist (item-name item-names)
e9cb4479 1876 (plstore-delete store item-name))
f3078a00 1877 (plstore-save store)))
8977de27
DU
1878 items))
1879
1880(defun* auth-source-plstore-create (&rest spec
e9cb4479
DU
1881 &key backend
1882 secret host user port create
1883 &allow-other-keys)
8977de27 1884 (let* ((base-required '(host user port secret))
e9cb4479 1885 (base-secret '(secret))
8977de27
DU
1886 ;; we know (because of an assertion in auth-source-search) that the
1887 ;; :create parameter is either t or a list (which includes nil)
1888 (create-extra (if (eq t create) nil create))
e9cb4479
DU
1889 (current-data (car (auth-source-search :max 1
1890 :host host
1891 :port port)))
8977de27
DU
1892 (required (append base-required create-extra))
1893 (file (oref backend source))
1894 (add "")
1895 ;; `valist' is an alist
1896 valist
1897 ;; `artificial' will be returned if no creation is needed
1898 artificial
e9cb4479 1899 secret-artificial)
8977de27
DU
1900
1901 ;; only for base required elements (defined as function parameters):
1902 ;; fill in the valist with whatever data we may have from the search
1903 ;; we complete the first value if it's a list and use the value otherwise
1904 (dolist (br base-required)
1905 (when (symbol-value br)
1906 (let ((br-choice (cond
1907 ;; all-accepting choice (predicate is t)
1908 ((eq t (symbol-value br)) nil)
1909 ;; just the value otherwise
1910 (t (symbol-value br)))))
1911 (when br-choice
8b6c19f4 1912 (auth-source--aput valist br br-choice)))))
8977de27
DU
1913
1914 ;; for extra required elements, see if the spec includes a value for them
1915 (dolist (er create-extra)
1916 (let ((name (concat ":" (symbol-name er)))
1917 (keys (loop for i below (length spec) by 2
1918 collect (nth i spec))))
1919 (dolist (k keys)
1920 (when (equal (symbol-name k) name)
8b6c19f4 1921 (auth-source--aput valist er (plist-get spec k))))))
8977de27
DU
1922
1923 ;; for each required element
1924 (dolist (r required)
8b6c19f4 1925 (let* ((data (auth-source--aget valist r))
8977de27
DU
1926 ;; take the first element if the data is a list
1927 (data (or (auth-source-netrc-element-or-first data)
e9cb4479
DU
1928 (plist-get current-data
1929 (intern (format ":%s" r) obarray))))
8977de27 1930 ;; this is the default to be offered
8b6c19f4
SM
1931 (given-default (auth-source--aget
1932 auth-source-creation-defaults r))
8977de27
DU
1933 ;; the default supplementals are simple:
1934 ;; for the user, try `given-default' and then (user-login-name);
1935 ;; otherwise take `given-default'
1936 (default (cond
1937 ((and (not given-default) (eq r 'user))
1938 (user-login-name))
1939 (t given-default)))
1940 (printable-defaults (list
1941 (cons 'user
1942 (or
1943 (auth-source-netrc-element-or-first
8b6c19f4 1944 (auth-source--aget valist 'user))
8977de27
DU
1945 (plist-get artificial :user)
1946 "[any user]"))
1947 (cons 'host
1948 (or
1949 (auth-source-netrc-element-or-first
8b6c19f4 1950 (auth-source--aget valist 'host))
8977de27
DU
1951 (plist-get artificial :host)
1952 "[any host]"))
1953 (cons 'port
1954 (or
1955 (auth-source-netrc-element-or-first
8b6c19f4 1956 (auth-source--aget valist 'port))
8977de27
DU
1957 (plist-get artificial :port)
1958 "[any port]"))))
8b6c19f4 1959 (prompt (or (auth-source--aget auth-source-creation-prompts r)
8977de27
DU
1960 (case r
1961 (secret "%p password for %u@%h: ")
1962 (user "%p user name for %h: ")
1963 (host "%p host name for user %u: ")
1964 (port "%p port for %u@%h: "))
1965 (format "Enter %s (%%u@%%h:%%p): " r)))
1966 (prompt (auth-source-format-prompt
1967 prompt
8b6c19f4
SM
1968 `((?u ,(auth-source--aget printable-defaults 'user))
1969 (?h ,(auth-source--aget printable-defaults 'host))
1970 (?p ,(auth-source--aget printable-defaults 'port))))))
8977de27
DU
1971
1972 ;; Store the data, prompting for the password if needed.
5c7f66a0
G
1973 (setq data (or data
1974 (if (eq r 'secret)
1975 (or (eval default) (read-passwd prompt))
1976 (if (stringp default)
8b6c19f4
SM
1977 (read-string
1978 (if (string-match ": *\\'" prompt)
1979 (concat (substring prompt 0 (match-beginning 0))
1980 " (default " default "): ")
1981 (concat prompt "(default " default ") "))
1982 nil nil default)
5c7f66a0 1983 (eval default)))))
8977de27
DU
1984
1985 (when data
e9cb4479
DU
1986 (if (member r base-secret)
1987 (setq secret-artificial
1988 (plist-put secret-artificial
1989 (intern (concat ":" (symbol-name r)))
1990 data))
1991 (setq artificial (plist-put artificial
1992 (intern (concat ":" (symbol-name r)))
1993 data))))))
b09c3fe0 1994 (plstore-put (oref backend data)
e9cb4479
DU
1995 (sha1 (format "%s@%s:%s"
1996 (plist-get artificial :user)
1997 (plist-get artificial :host)
1998 (plist-get artificial :port)))
1999 artificial secret-artificial)
8977de27 2000 (if (y-or-n-p (format "Save auth info to file %s? "
e9cb4479
DU
2001 (plstore-get-file (oref backend data))))
2002 (plstore-save (oref backend data)))))
8977de27 2003
b8e0f0cd
G
2004;;; older API
2005
cbffd0bd 2006;; (auth-source-user-or-password '("login" "password") "imap.myhost.com" t "tzz")
b8e0f0cd
G
2007
2008;; deprecate the old interface
2009(make-obsolete 'auth-source-user-or-password
2010 'auth-source-search "Emacs 24.1")
2011(make-obsolete 'auth-source-forget-user-or-password
2012 'auth-source-forget "Emacs 24.1")
fb178e4c 2013
0e4966fb 2014(defun auth-source-user-or-password
35123c04
TZ
2015 (mode host port &optional username create-missing delete-existing)
2016 "Find MODE (string or list of strings) matching HOST and PORT.
fb178e4c 2017
b8e0f0cd
G
2018DEPRECATED in favor of `auth-source-search'!
2019
fb178e4c
KY
2020USERNAME is optional and will be used as \"login\" in a search
2021across the Secret Service API (see secrets.el) if the resulting
2022items don't have a username. This means that if you search for
2023username \"joe\" and it matches an item but the item doesn't have
2024a :user attribute, the username \"joe\" will be returned.
2025
0e4966fb
MA
2026A non nil DELETE-EXISTING means deleting any matching password
2027entry in the respective sources. This is useful only when
2028CREATE-MISSING is non nil as well; the intended use case is to
2029remove wrong password entries.
2030
2031If no matching entry is found, and CREATE-MISSING is non nil,
2032the password will be retrieved interactively, and it will be
2033stored in the password database which matches best (see
2034`auth-sources').
2035
2036MODE can be \"login\" or \"password\"."
554a69b8 2037 (auth-source-do-debug
b8e0f0cd 2038 "auth-source-user-or-password: DEPRECATED get %s for %s (%s) + user=%s"
35123c04 2039 mode host port username)
b8e0f0cd 2040
3b36c17e 2041 (let* ((listy (listp mode))
cbabe91f
TZ
2042 (mode (if listy mode (list mode)))
2043 (cname (if username
35123c04
TZ
2044 (format "%s %s:%s %s" mode host port username)
2045 (format "%s %s:%s" mode host port)))
2046 (search (list :host host :port port))
cbabe91f 2047 (search (if username (append search (list :user username)) search))
b8e0f0cd
G
2048 (search (if create-missing
2049 (append search (list :create t))
2050 search))
2051 (search (if delete-existing
2052 (append search (list :delete t))
2053 search))
2054 ;; (found (if (not delete-existing)
2055 ;; (gethash cname auth-source-cache)
2056 ;; (remhash cname auth-source-cache)
2057 ;; nil)))
2058 (found nil))
ed778fad 2059 (if found
cbabe91f
TZ
2060 (progn
2061 (auth-source-do-debug
b8e0f0cd 2062 "auth-source-user-or-password: DEPRECATED cached %s=%s for %s (%s) + %s"
cbabe91f
TZ
2063 mode
2064 ;; don't show the password
b8e0f0cd 2065 (if (and (member "password" mode) t)
cbabe91f
TZ
2066 "SECRET"
2067 found)
35123c04 2068 host port username)
cbabe91f 2069 found) ; return the found data
b8e0f0cd
G
2070 ;; else, if not found, search with a max of 1
2071 (let ((choice (nth 0 (apply 'auth-source-search
2072 (append '(:max 1) search)))))
2073 (when choice
2074 (dolist (m mode)
2075 (cond
2076 ((equal "password" m)
2077 (push (if (plist-get choice :secret)
e9cb4479
DU
2078 (funcall (plist-get choice :secret))
2079 nil) found))
b8e0f0cd
G
2080 ((equal "login" m)
2081 (push (plist-get choice :user) found)))))
2082 (setq found (nreverse found))
2083 (setq found (if listy found (car-safe found)))))
9b3ebcb6 2084
e9cb4479 2085 found))
8f7abae3 2086
fb7e9e05
TZ
2087(defun auth-source-user-and-password (host &optional user)
2088 (let* ((auth-info (car
2089 (if user
2090 (auth-source-search
2091 :host host
2092 :user "yourusername"
2093 :max 1
2094 :require '(:user :secret)
2095 :create nil)
2096 (auth-source-search
2097 :host host
2098 :max 1
2099 :require '(:user :secret)
2100 :create nil))))
2101 (user (plist-get auth-info :user))
2102 (password (plist-get auth-info :secret)))
2103 (when (functionp password)
2104 (setq password (funcall password)))
2105 (list user password auth-info)))
2106
8f7abae3
MB
2107(provide 'auth-source)
2108
8f7abae3 2109;;; auth-source.el ends here