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