Output alists with dotted pair notation in .dir-locals.el
[emacs.git] / lisp / auth-source.el
blobeb262a13df4f812477d14db288e9d8e924199c1d
1 ;;; auth-source.el --- authentication sources for Gnus and Emacs -*- lexical-binding: t -*-
3 ;; Copyright (C) 2008-2018 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 <https://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 'json)
43 (require 'password-cache)
45 (eval-when-compile (require 'cl-lib))
46 (require 'eieio)
48 (autoload 'secrets-create-item "secrets")
49 (autoload 'secrets-delete-item "secrets")
50 (autoload 'secrets-get-alias "secrets")
51 (autoload 'secrets-get-attributes "secrets")
52 (autoload 'secrets-get-secret "secrets")
53 (autoload 'secrets-list-collections "secrets")
54 (autoload 'secrets-search-items "secrets")
56 (autoload 'rfc2104-hash "rfc2104")
58 (autoload 'plstore-open "plstore")
59 (autoload 'plstore-find "plstore")
60 (autoload 'plstore-put "plstore")
61 (autoload 'plstore-delete "plstore")
62 (autoload 'plstore-save "plstore")
63 (autoload 'plstore-get-file "plstore")
65 (eval-when-compile (require 'epg)) ;; setf-method for `epg-context-armor'
66 (autoload 'epg-make-context "epg")
67 (autoload 'epg-context-set-passphrase-callback "epg")
68 (autoload 'epg-decrypt-string "epg")
69 (autoload 'epg-encrypt-string "epg")
71 (autoload 'help-mode "help-mode" nil t)
73 (defvar secrets-enabled)
75 (defgroup auth-source nil
76 "Authentication sources."
77 :version "23.1" ;; No Gnus
78 :group 'gnus)
80 ;;;###autoload
81 (defcustom auth-source-cache-expiry 7200
82 "How many seconds passwords are cached, or nil to disable
83 expiring. Overrides `password-cache-expiry' through a
84 let-binding."
85 :version "24.1"
86 :group 'auth-source
87 :type '(choice (const :tag "Never" nil)
88 (const :tag "All Day" 86400)
89 (const :tag "2 Hours" 7200)
90 (const :tag "30 Minutes" 1800)
91 (integer :tag "Seconds")))
93 ;; The slots below correspond with the `auth-source-search' spec,
94 ;; so a backend with :host set, for instance, would match only
95 ;; searches for that host. Normally they are nil.
96 (defclass auth-source-backend ()
97 ((type :initarg :type
98 :initform 'netrc
99 :type symbol
100 :custom symbol
101 :documentation "The backend type.")
102 (source :initarg :source
103 :type string
104 :custom string
105 :documentation "The backend source.")
106 (host :initarg :host
107 :initform t
108 :type t
109 :custom string
110 :documentation "The backend host.")
111 (user :initarg :user
112 :initform t
113 :type t
114 :custom string
115 :documentation "The backend user.")
116 (port :initarg :port
117 :initform t
118 :type t
119 :custom string
120 :documentation "The backend protocol.")
121 (data :initarg :data
122 :initform nil
123 :documentation "Internal backend data.")
124 (create-function :initarg :create-function
125 :initform ignore
126 :type function
127 :custom function
128 :documentation "The create function.")
129 (search-function :initarg :search-function
130 :initform ignore
131 :type function
132 :custom function
133 :documentation "The search function.")))
135 (defcustom auth-source-protocols '((imap "imap" "imaps" "143" "993")
136 (pop3 "pop3" "pop" "pop3s" "110" "995")
137 (ssh "ssh" "22")
138 (sftp "sftp" "115")
139 (smtp "smtp" "25"))
140 "List of authentication protocols and their names"
142 :group 'auth-source
143 :version "23.2" ;; No Gnus
144 :type '(repeat :tag "Authentication Protocols"
145 (cons :tag "Protocol Entry"
146 (symbol :tag "Protocol")
147 (repeat :tag "Names"
148 (string :tag "Name")))))
150 ;; Generate all the protocols in a format Customize can use.
151 ;; TODO: generate on the fly from auth-source-protocols
152 (defconst auth-source-protocols-customize
153 (mapcar (lambda (a)
154 (let ((p (car-safe a)))
155 (list 'const
156 :tag (upcase (symbol-name p))
157 p)))
158 auth-source-protocols))
160 (defvar auth-source-creation-defaults nil
161 ;; FIXME: AFAICT this is not set (or let-bound) anywhere!
162 "Defaults for creating token values. Usually let-bound.")
164 (defvar auth-source-creation-prompts nil
165 "Default prompts for token values. Usually let-bound.")
167 (make-obsolete 'auth-source-hide-passwords nil "Emacs 24.1")
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)))
179 ;; 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)))
180 ;; TODO: or maybe leave as (setq auth-source-netrc-use-gpg-tokens 'never)
182 (defcustom auth-source-netrc-use-gpg-tokens 'never
183 "Set this to tell auth-source when to create GPG password
184 tokens in netrc files. It's either an alist or `never'.
185 Note that if EPA/EPG is not available, this should NOT be used."
186 :group 'auth-source
187 :version "23.2" ;; No Gnus
188 :type `(choice
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 epa-file-auto-mode-alist-entry)
198 "\\.gpg\\'"))
199 (regexp :tag "Regular expression"))
200 (choice :tag "What to do"
201 (const :tag "Save GPG-encrypted password tokens" gpg)
202 (const :tag "Don't encrypt tokens" never))))))
204 (defcustom auth-source-do-cache t
205 "Whether auth-source should cache information with `password-cache'."
206 :group 'auth-source
207 :version "23.2" ;; No Gnus
208 :type `boolean)
210 (defcustom auth-source-debug nil
211 "Whether auth-source should log debug messages.
213 If the value is nil, debug messages are not logged.
215 If the value is t, debug messages are logged with `message'. In
216 that case, your authentication data will be in the clear (except
217 for passwords).
219 If the value is a function, debug messages are logged by calling
220 that function using the same arguments as `message'."
221 :group 'auth-source
222 :version "23.2" ;; No Gnus
223 :type `(choice
224 :tag "auth-source debugging mode"
225 (const :tag "Log using `message' to the *Messages* buffer" t)
226 (const :tag "Log all trivia with `message' to the *Messages* buffer"
227 trivia)
228 (function :tag "Function that takes arguments like `message'")
229 (const :tag "Don't log anything" nil)))
231 (defcustom auth-sources '("~/.authinfo" "~/.authinfo.gpg" "~/.netrc")
232 "List of authentication sources.
233 Each entry is the authentication type with optional properties.
234 Entries are tried in the order in which they appear.
235 See Info node `(auth)Help for users' for details.
237 If an entry names a file with the \".gpg\" extension and you have
238 EPA/EPG set up, the file will be encrypted and decrypted
239 automatically. See Info node `(epa)Encrypting/decrypting gpg files'
240 for details.
242 It's best to customize this with `\\[customize-variable]' because the choices
243 can get pretty complex."
244 :group 'auth-source
245 :version "26.1" ; neither new nor changed default
246 :type `(repeat :tag "Authentication Sources"
247 (choice
248 (string :tag "Just a file")
249 (const :tag "Default Secrets API Collection" default)
250 (const :tag "Login Secrets API Collection" "secrets:Login")
251 (const :tag "Temp Secrets API Collection" "secrets:session")
253 (const :tag "Default internet Mac OS Keychain"
254 macos-keychain-internet)
256 (const :tag "Default generic Mac OS Keychain"
257 macos-keychain-generic)
259 (list :tag "Source definition"
260 (const :format "" :value :source)
261 (choice :tag "Authentication backend choice"
262 (string :tag "Authentication Source (file)")
263 (list
264 :tag "Secret Service API/KWallet/GNOME Keyring"
265 (const :format "" :value :secrets)
266 (choice :tag "Collection to use"
267 (string :tag "Collection name")
268 (const :tag "Default" default)
269 (const :tag "Login" "Login")
270 (const
271 :tag "Temporary" "session")))
272 (list
273 :tag "Mac OS internet Keychain"
274 (const :format ""
275 :value :macos-keychain-internet)
276 (choice :tag "Collection to use"
277 (string :tag "internet Keychain path")
278 (const :tag "default" default)))
279 (list
280 :tag "Mac OS generic Keychain"
281 (const :format ""
282 :value :macos-keychain-generic)
283 (choice :tag "Collection to use"
284 (string :tag "generic Keychain path")
285 (const :tag "default" default))))
286 (repeat :tag "Extra Parameters" :inline t
287 (choice :tag "Extra parameter"
288 (list
289 :tag "Host"
290 (const :format "" :value :host)
291 (choice :tag "Host (machine) choice"
292 (const :tag "Any" t)
293 (regexp
294 :tag "Regular expression")))
295 (list
296 :tag "Protocol"
297 (const :format "" :value :port)
298 (choice
299 :tag "Protocol"
300 (const :tag "Any" t)
301 ,@auth-source-protocols-customize))
302 (list :tag "User" :inline t
303 (const :format "" :value :user)
304 (choice
305 :tag "Personality/Username"
306 (const :tag "Any" t)
307 (string
308 :tag "Name"))))))
309 (sexp :tag "A data structure (external provider)"))))
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 (defun auth-source-do-debug (&rest msg)
321 (when auth-source-debug
322 (apply #'auth-source-do-warn msg)))
324 (defun auth-source-do-trivia (&rest msg)
325 (when (or (eq auth-source-debug 'trivia)
326 (functionp auth-source-debug))
327 (apply #'auth-source-do-warn msg)))
329 (defun auth-source-do-warn (&rest msg)
330 (apply
331 ;; set logger to either the function in auth-source-debug or 'message
332 ;; note that it will be 'message if auth-source-debug is nil
333 (if (functionp auth-source-debug)
334 auth-source-debug
335 'message)
336 msg))
338 (defun auth-source-read-char-choice (prompt choices)
339 "Read one of CHOICES by `read-char-choice', or `read-char'.
340 `dropdown-list' support is disabled because it doesn't work reliably.
341 Only one of CHOICES will be returned. The PROMPT is augmented
342 with \"[a/b/c] \" if CHOICES is \(?a ?b ?c)."
343 (when choices
344 (let* ((prompt-choices
345 (apply #'concat
346 (cl-loop for c in choices collect (format "%c/" c))))
347 (prompt-choices (concat "[" (substring prompt-choices 0 -1) "] "))
348 (full-prompt (concat prompt prompt-choices))
351 (while (not (memq k choices))
352 (setq k (read-char-choice full-prompt choices)))
353 k)))
355 (defvar auth-source-backend-parser-functions nil
356 "List of auth-source parser functions.
357 Each function takes an entry from `auth-sources' as parameter and
358 returns a backend or nil if the entry is not supported. Add a
359 parser function to this list with `add-hook'. Searching for a
360 backend starts with the first element on the list and stops as
361 soon as a function returns non-nil.")
363 (defun auth-source-backend-parse (entry)
364 "Create an auth-source-backend from an ENTRY in `auth-sources'."
366 (let (backend)
367 (cl-dolist (f auth-source-backend-parser-functions)
368 (when (setq backend (funcall f entry))
369 (cl-return)))
371 (unless backend
372 ;; none of the parsers worked
373 (auth-source-do-warn
374 "auth-source-backend-parse: invalid backend spec: %S" entry)
375 (setq backend (make-instance 'auth-source-backend
376 :source ""
377 :type 'ignore)))
378 (auth-source-backend-parse-parameters entry backend)))
380 (defun auth-source-backends-parser-file (entry)
381 ;; take just a file name use it as a netrc/plist file
382 ;; matching any user, host, and protocol
383 (when (stringp entry)
384 (setq entry (list :source entry)))
385 (let* ((source (plist-get entry :source))
386 (source-without-gpg
387 (if (and (stringp source)
388 (equal (file-name-extension source) "gpg"))
389 (file-name-sans-extension source)
390 (or source "")))
391 (extension (or (and (stringp source-without-gpg)
392 (file-name-extension source-without-gpg))
393 "")))
394 (when (stringp source)
395 (cond
396 ((equal extension "plist")
397 (auth-source-backend
398 source
399 :source source
400 :type 'plstore
401 :search-function #'auth-source-plstore-search
402 :create-function #'auth-source-plstore-create
403 :data (plstore-open source)))
404 ((member-ignore-case extension '("json"))
405 (auth-source-backend
406 source
407 :source source
408 :type 'json
409 :search-function #'auth-source-json-search))
411 (auth-source-backend
412 source
413 :source source
414 :type 'netrc
415 :search-function #'auth-source-netrc-search
416 :create-function #'auth-source-netrc-create))))))
418 ;; Note this function should be last in the parser functions, so we add it first
419 (add-hook 'auth-source-backend-parser-functions 'auth-source-backends-parser-file)
421 (defun auth-source-backends-parser-macos-keychain (entry)
422 ;; take macos-keychain-{internet,generic}:XYZ and use it as macOS
423 ;; Keychain "XYZ" matching any user, host, and protocol
424 (when (and (stringp entry) (string-match "^macos-keychain-internet:\\(.+\\)"
425 entry))
426 (setq entry `(:source (:macos-keychain-internet
427 ,(match-string 1 entry)))))
428 (when (and (stringp entry) (string-match "^macos-keychain-generic:\\(.+\\)"
429 entry))
430 (setq entry `(:source (:macos-keychain-generic
431 ,(match-string 1 entry)))))
432 ;; take 'macos-keychain-internet or generic and use it as a Mac OS
433 ;; Keychain collection matching any user, host, and protocol
434 (when (eq entry 'macos-keychain-internet)
435 (setq entry '(:source (:macos-keychain-internet default))))
436 (when (eq entry 'macos-keychain-generic)
437 (setq entry '(:source (:macos-keychain-generic default))))
438 (cond
439 ;; the macOS Keychain
440 ((and
441 (not (null (plist-get entry :source))) ; the source must not be nil
442 (listp (plist-get entry :source)) ; and it must be a list
444 (plist-get (plist-get entry :source) :macos-keychain-generic)
445 (plist-get (plist-get entry :source) :macos-keychain-internet)))
447 (let* ((source-spec (plist-get entry :source))
448 (keychain-generic (plist-get source-spec :macos-keychain-generic))
449 (keychain-type (if keychain-generic
450 'macos-keychain-generic
451 'macos-keychain-internet))
452 (source (plist-get source-spec (if keychain-generic
453 :macos-keychain-generic
454 :macos-keychain-internet))))
456 (when (symbolp source)
457 (setq source (symbol-name source)))
459 (auth-source-backend
460 (format "Mac OS Keychain (%s)" source)
461 :source source
462 :type keychain-type
463 :search-function #'auth-source-macos-keychain-search
464 :create-function #'auth-source-macos-keychain-create)))))
466 (add-hook 'auth-source-backend-parser-functions 'auth-source-backends-parser-macos-keychain)
468 (defun auth-source-backends-parser-secrets (entry)
469 ;; take secrets:XYZ and use it as Secrets API collection "XYZ"
470 ;; matching any user, host, and protocol
471 (when (and (stringp entry) (string-match "^secrets:\\(.+\\)" entry))
472 (setq entry `(:source (:secrets ,(match-string 1 entry)))))
473 ;; take 'default and use it as a Secrets API default collection
474 ;; matching any user, host, and protocol
475 (when (eq entry 'default)
476 (setq entry '(:source (:secrets default))))
477 (cond
478 ;; the Secrets API. We require the package, in order to have a
479 ;; defined value for `secrets-enabled'.
480 ((and
481 (not (null (plist-get entry :source))) ; the source must not be nil
482 (listp (plist-get entry :source)) ; and it must be a list
483 (not (null (plist-get
484 (plist-get entry :source)
485 :secrets))) ; the source must have :secrets
486 (require 'secrets nil t) ; and we must load the Secrets API
487 secrets-enabled) ; and that API must be enabled
489 ;; the source is either the :secrets key in ENTRY or
490 ;; if that's missing or nil, it's "session"
491 (let ((source (plist-get (plist-get entry :source) :secrets)))
493 ;; if the source is a symbol, we look for the alias named so,
494 ;; and if that alias is missing, we use "Login"
495 (when (symbolp source)
496 (setq source (or (secrets-get-alias (symbol-name source))
497 "Login")))
499 (if (featurep 'secrets)
500 (auth-source-backend
501 (format "Secrets API (%s)" source)
502 :source source
503 :type 'secrets
504 :search-function #'auth-source-secrets-search
505 :create-function #'auth-source-secrets-create)
506 (auth-source-do-warn
507 "auth-source-backend-parse: no Secrets API, ignoring spec: %S" entry)
508 (auth-source-backend
509 (format "Ignored Secrets API (%s)" source)
510 :source ""
511 :type 'ignore))))))
513 (add-hook 'auth-source-backend-parser-functions 'auth-source-backends-parser-secrets)
515 (defun auth-source-backend-parse-parameters (entry backend)
516 "Fills in the extra auth-source-backend parameters of ENTRY.
517 Using the plist ENTRY, get the :host, :port, and :user search
518 parameters."
519 (let ((entry (if (stringp entry)
521 entry))
522 val)
523 (when (setq val (plist-get entry :host))
524 (oset backend host val))
525 (when (setq val (plist-get entry :user))
526 (oset backend user val))
527 (when (setq val (plist-get entry :port))
528 (oset backend port val)))
529 backend)
531 ;; (mapcar 'auth-source-backend-parse auth-sources)
533 (cl-defun auth-source-search (&rest spec
534 &key max require create delete
535 &allow-other-keys)
536 "Search or modify authentication backends according to SPEC.
538 This function parses `auth-sources' for matches of the SPEC
539 plist. It can optionally create or update an authentication
540 token if requested. A token is just a standard Emacs property
541 list with a :secret property that can be a function; all the
542 other properties will always hold scalar values.
544 Typically the :secret property, if present, contains a password.
546 Common search keys are :max, :host, :port, and :user. In
547 addition, :create specifies if and how tokens will be created.
548 Finally, :type can specify which backend types you want to check.
550 A string value is always matched literally. A symbol is matched
551 as its string value, literally. All the SPEC values can be
552 single values (symbol or string) or lists thereof (in which case
553 any of the search terms matches).
555 :create t means to create a token if possible.
557 A new token will be created if no matching tokens were found.
558 The new token will have only the keys the backend requires. For
559 the netrc backend, for instance, that's the user, host, and
560 port keys.
562 Here's an example:
564 \(let ((auth-source-creation-defaults \\='((user . \"defaultUser\")
565 (A . \"default A\"))))
566 (auth-source-search :host \"mine\" :type \\='netrc :max 1
567 :P \"pppp\" :Q \"qqqq\"
568 :create t))
570 which says:
572 \"Search for any entry matching host `mine' in backends of type
573 `netrc', maximum one result.
575 Create a new entry if you found none. The netrc backend will
576 automatically require host, user, and port. The host will be
577 `mine'. We prompt for the user with default `defaultUser' and
578 for the port without a default. We will not prompt for A, Q,
579 or P. The resulting token will only have keys user, host, and
580 port.\"
582 :create \\='(A B C) also means to create a token if possible.
584 The behavior is like :create t but if the list contains any
585 parameter, that parameter will be required in the resulting
586 token. The value for that parameter will be obtained from the
587 search parameters or from user input. If any queries are needed,
588 the alist `auth-source-creation-defaults' will be checked for the
589 default value. If the user, host, or port are missing, the alist
590 `auth-source-creation-prompts' will be used to look up the
591 prompts IN THAT ORDER (so the `user' prompt will be queried first,
592 then `host', then `port', and finally `secret'). Each prompt string
593 can use %u, %h, and %p to show the user, host, and port.
595 Here's an example:
597 \(let ((auth-source-creation-defaults \\='((user . \"defaultUser\")
598 (A . \"default A\")))
599 (auth-source-creation-prompts
600 \\='((password . \"Enter IMAP password for %h:%p: \"))))
601 (auth-source-search :host \\='(\"nonesuch\" \"twosuch\") :type \\='netrc :max 1
602 :P \"pppp\" :Q \"qqqq\"
603 :create \\='(A B Q)))
605 which says:
607 \"Search for any entry matching host `nonesuch'
608 or `twosuch' in backends of type `netrc', maximum one result.
610 Create a new entry if you found none. The netrc backend will
611 automatically require host, user, and port. The host will be
612 `nonesuch' and Q will be `qqqq'. We prompt for the password
613 with the shown prompt. We will not prompt for Q. The resulting
614 token will have keys user, host, port, A, B, and Q. It will not
615 have P with any value, even though P is used in the search to
616 find only entries that have P set to `pppp'.\"
618 When multiple values are specified in the search parameter, the
619 user is prompted for which one. So :host (X Y Z) would ask the
620 user to choose between X, Y, and Z.
622 This creation can fail if the search was not specific enough to
623 create a new token (it's up to the backend to decide that). You
624 should `catch' the backend-specific error as usual. Some
625 backends (netrc, at least) will prompt the user rather than throw
626 an error.
628 :require (A B C) means that only results that contain those
629 tokens will be returned. Thus for instance requiring :secret
630 will ensure that any results will actually have a :secret
631 property.
633 :delete t means to delete any found entries. nil by default.
634 Use `auth-source-delete' in ELisp code instead of calling
635 `auth-source-search' directly with this parameter.
637 :type (X Y Z) will check only those backend types. `netrc' and
638 `secrets' are the only ones supported right now.
640 :max N means to try to return at most N items (defaults to 1).
641 More than N items may be returned, depending on the search and
642 the backend.
644 When :max is 0 the function will return just t or nil to indicate
645 if any matches were found.
647 :host (X Y Z) means to match only hosts X, Y, or Z according to
648 the match rules above. Defaults to t.
650 :user (X Y Z) means to match only users X, Y, or Z according to
651 the match rules above. Defaults to t.
653 :port (P Q R) means to match only protocols P, Q, or R.
654 Defaults to t.
656 :K (V1 V2 V3) for any other key K will match values V1, V2, or
657 V3 (note the match rules above).
659 The return value is a list with at most :max tokens. Each token
660 is a plist with keys :backend :host :port :user, plus any other
661 keys provided by the backend (notably :secret). But note the
662 exception for :max 0, which see above.
664 The token can hold a :save-function key. If you call that, the
665 user will be prompted to save the data to the backend. You can't
666 request that this should happen right after creation, because
667 `auth-source-search' has no way of knowing if the token is
668 actually useful. So the caller must arrange to call this function.
670 The token's :secret key can hold a function. In that case you
671 must call it to obtain the actual value."
672 (let* ((backends (mapcar #'auth-source-backend-parse auth-sources))
673 (max (or max 1))
674 (ignored-keys '(:require :create :delete :max))
675 (keys (cl-loop for i below (length spec) by 2
676 unless (memq (nth i spec) ignored-keys)
677 collect (nth i spec)))
678 (cached (auth-source-remembered-p spec))
679 ;; note that we may have cached results but found is still nil
680 ;; (there were no results from the search)
681 (found (auth-source-recall spec))
682 filtered-backends)
684 (if (and cached auth-source-do-cache)
685 (auth-source-do-debug
686 "auth-source-search: found %d CACHED results matching %S"
687 (length found) spec)
689 (cl-assert
690 (or (eq t create) (listp create)) t
691 "Invalid auth-source :create parameter (must be t or a list): %s %s")
693 (cl-assert
694 (listp require) t
695 "Invalid auth-source :require parameter (must be a list): %s")
697 (setq filtered-backends (copy-sequence backends))
698 (dolist (backend backends)
699 (cl-dolist (key keys)
700 ;; ignore invalid slots
701 (condition-case nil
702 (unless (auth-source-search-collection
703 (plist-get spec key)
704 (slot-value backend key))
705 (setq filtered-backends (delq backend filtered-backends))
706 (cl-return))
707 (invalid-slot-name nil))))
709 (auth-source-do-trivia
710 "auth-source-search: found %d backends matching %S"
711 (length filtered-backends) spec)
713 ;; (debug spec "filtered" filtered-backends)
714 ;; First go through all the backends without :create, so we can
715 ;; query them all.
716 (setq found (auth-source-search-backends filtered-backends
717 spec
718 ;; to exit early
720 ;; create is always nil here
721 nil delete
722 require))
724 (auth-source-do-debug
725 "auth-source-search: found %d results (max %d) matching %S"
726 (length found) max spec)
728 ;; If we didn't find anything, then we allow the backend(s) to
729 ;; create the entries.
730 (when (and create
731 (not found))
732 (setq found (auth-source-search-backends filtered-backends
733 spec
734 ;; to exit early
736 create delete
737 require))
738 (auth-source-do-debug
739 "auth-source-search: CREATED %d results (max %d) matching %S"
740 (length found) max spec))
742 ;; note we remember the lack of result too, if it's applicable
743 (when auth-source-do-cache
744 (auth-source-remember spec found)))
746 (if (zerop max)
747 (not (null found))
748 found)))
750 (defun auth-source-search-backends (backends spec max create delete require)
751 (let ((max (if (zerop max) 1 max)) ; stop with 1 match if we're asked for zero
752 matches)
753 (dolist (backend backends)
754 (when (> max (length matches)) ; if we need more matches...
755 (let* ((bmatches (apply
756 (slot-value backend 'search-function)
757 :backend backend
758 :type (slot-value backend 'type)
759 ;; note we're overriding whatever the spec
760 ;; has for :max, :require, :create, and :delete
761 :max max
762 :require require
763 :create create
764 :delete delete
765 spec)))
766 (when bmatches
767 (auth-source-do-trivia
768 "auth-source-search-backend: got %d (max %d) in %s:%s matching %S"
769 (length bmatches) max
770 (slot-value backend 'type)
771 (slot-value backend 'source)
772 spec)
773 (setq matches (append matches bmatches))))))
774 matches))
776 (defun auth-source-delete (&rest spec)
777 "Delete entries from the authentication backends according to SPEC.
778 Calls `auth-source-search' with the :delete property in SPEC set to t.
779 The backend may not actually delete the entries.
781 Returns the deleted entries."
782 (apply #'auth-source-search (plist-put spec :delete t)))
784 (defun auth-source-search-collection (collection value)
785 "Returns t is VALUE is t or COLLECTION is t or COLLECTION contains VALUE."
786 (when (and (atom collection) (not (eq t collection)))
787 (setq collection (list collection)))
789 ;; (debug :collection collection :value value)
790 (or (eq collection t)
791 (eq value t)
792 (equal collection value)
793 (member value collection)))
795 (defvar auth-source-netrc-cache nil)
797 (defun auth-source-forget-all-cached ()
798 "Forget all cached auth-source data."
799 (interactive)
800 (maphash (lambda (key _password)
801 (when (eq 'auth-source (car-safe key))
802 ;; remove that key
803 (password-cache-remove key)))
804 password-data)
805 (setq auth-source-netrc-cache nil))
807 (defun auth-source-format-cache-entry (spec)
808 "Format SPEC entry to put it in the password cache."
809 `(auth-source . ,spec))
811 (defun auth-source-remember (spec found)
812 "Remember FOUND search results for SPEC."
813 (let ((password-cache-expiry auth-source-cache-expiry))
814 (password-cache-add
815 (auth-source-format-cache-entry spec) found)))
817 (defun auth-source-recall (spec)
818 "Recall FOUND search results for SPEC."
819 (password-read-from-cache (auth-source-format-cache-entry spec)))
821 (defun auth-source-remembered-p (spec)
822 "Check if SPEC is remembered."
823 (password-in-cache-p
824 (auth-source-format-cache-entry spec)))
826 (defun auth-source-forget (spec)
827 "Forget any cached data matching SPEC exactly.
829 This is the same SPEC you passed to `auth-source-search'.
830 Returns t or nil for forgotten or not found."
831 (password-cache-remove (auth-source-format-cache-entry spec)))
833 (defun auth-source-forget+ (&rest spec)
834 "Forget any cached data matching SPEC. Returns forgotten count.
836 This is not a full `auth-source-search' spec but works similarly.
837 For instance, \(:host \"myhost\" \"yourhost\") would find all the
838 cached data that was found with a search for those two hosts,
839 while \(:host t) would find all host entries."
840 (let ((count 0))
841 (maphash
842 (lambda (key _password)
843 (when (and (eq 'auth-source (car-safe key))
844 ;; and the spec matches what was stored in the cache
845 (auth-source-specmatchp spec (cdr key)))
846 ;; remove that key
847 (password-cache-remove key)
848 (cl-incf count)))
849 password-data)
850 count))
852 (defun auth-source-specmatchp (spec stored)
853 (let ((keys (cl-loop for i below (length spec) by 2
854 collect (nth i spec))))
855 (not (eq
856 (cl-dolist (key keys)
857 (unless (auth-source-search-collection (plist-get stored key)
858 (plist-get spec key))
859 (cl-return 'no)))
860 'no))))
862 (defun auth-source-pick-first-password (&rest spec)
863 "Pick the first secret found from applying SPEC to `auth-source-search'."
864 (let* ((result (nth 0 (apply #'auth-source-search (plist-put spec :max 1))))
865 (secret (plist-get result :secret)))
867 (if (functionp secret)
868 (funcall secret)
869 secret)))
871 (defun auth-source-format-prompt (prompt alist)
872 "Format PROMPT using %x (for any character x) specifiers in ALIST."
873 (dolist (cell alist)
874 (let ((c (nth 0 cell))
875 (v (nth 1 cell)))
876 (when (and c v)
877 (setq prompt (replace-regexp-in-string (format "%%%c" c)
878 (format "%s" v)
879 prompt nil t)))))
880 prompt)
882 (defun auth-source-ensure-strings (values)
883 (if (eq values t)
884 values
885 (unless (listp values)
886 (setq values (list values)))
887 (mapcar (lambda (value)
888 (if (numberp value)
889 (format "%s" value)
890 value))
891 values)))
893 ;;; Backend specific parsing: netrc/authinfo backend
895 (defun auth-source--aput-1 (alist key val)
896 (let ((seen ())
897 (rest alist))
898 (while (and (consp rest) (not (equal key (caar rest))))
899 (push (pop rest) seen))
900 (cons (cons key val)
901 (if (null rest) alist
902 (nconc (nreverse seen)
903 (if (equal key (caar rest)) (cdr rest) rest))))))
904 (defmacro auth-source--aput (var key val)
905 `(setq ,var (auth-source--aput-1 ,var ,key ,val)))
907 (defun auth-source--aget (alist key)
908 (cdr (assoc key alist)))
910 ;; (auth-source-netrc-parse :file "~/.authinfo.gpg")
911 (cl-defun auth-source-netrc-parse (&key file max host user port require
912 &allow-other-keys)
913 "Parse FILE and return a list of all entries in the file.
914 Note that the MAX parameter is used so we can exit the parse early."
915 (if (listp file)
916 ;; We got already parsed contents; just return it.
917 file
918 (when (file-exists-p file)
919 (setq port (auth-source-ensure-strings port))
920 (with-temp-buffer
921 (let* ((max (or max 5000)) ; sanity check: default to stop at 5K
922 (modified 0)
923 (cached (cdr-safe (assoc file auth-source-netrc-cache)))
924 (cached-mtime (plist-get cached :mtime))
925 (cached-secrets (plist-get cached :secret))
926 (check (lambda(alist)
927 (and alist
928 (auth-source-search-collection
929 host
931 (auth-source--aget alist "machine")
932 (auth-source--aget alist "host")
934 (auth-source-search-collection
935 user
937 (auth-source--aget alist "login")
938 (auth-source--aget alist "account")
939 (auth-source--aget alist "user")
941 (auth-source-search-collection
942 port
944 (auth-source--aget alist "port")
945 (auth-source--aget alist "protocol")
948 ;; the required list of keys is nil, or
949 (null require)
950 ;; every element of require is in n (normalized)
951 (let ((n (nth 0 (auth-source-netrc-normalize
952 (list alist) file))))
953 (cl-loop for req in require
954 always (plist-get n req)))))))
955 result)
957 (if (and (functionp cached-secrets)
958 (equal cached-mtime
959 (file-attribute-modification-time
960 (file-attributes file))))
961 (progn
962 (auth-source-do-trivia
963 "auth-source-netrc-parse: using CACHED file data for %s"
964 file)
965 (insert (funcall cached-secrets)))
966 (insert-file-contents file)
967 ;; cache all netrc files (used to be just .gpg files)
968 ;; Store the contents of the file heavily encrypted in memory.
969 ;; (note for the irony-impaired: they are just obfuscated)
970 (auth-source--aput
971 auth-source-netrc-cache file
972 (list :mtime (file-attribute-modification-time
973 (file-attributes file))
974 :secret (let ((v (mapcar #'1+ (buffer-string))))
975 (lambda () (apply #'string (mapcar #'1- v)))))))
976 (goto-char (point-min))
977 (let ((entries (auth-source-netrc-parse-entries check max))
978 alist)
979 (while (setq alist (pop entries))
980 (push (nreverse alist) result)))
982 (when (< 0 modified)
983 (when auth-source-gpg-encrypt-to
984 ;; (see bug#7487) making `epa-file-encrypt-to' local to
985 ;; this buffer lets epa-file skip the key selection query
986 ;; (see the `local-variable-p' check in
987 ;; `epa-file-write-region').
988 (unless (local-variable-p 'epa-file-encrypt-to (current-buffer))
989 (make-local-variable 'epa-file-encrypt-to))
990 (if (listp auth-source-gpg-encrypt-to)
991 (setq epa-file-encrypt-to auth-source-gpg-encrypt-to)))
993 ;; ask AFTER we've successfully opened the file
994 (when (y-or-n-p (format "Save file %s? (%d deletions)"
995 file modified))
996 (write-region (point-min) (point-max) file nil 'silent)
997 (auth-source-do-debug
998 "auth-source-netrc-parse: modified %d lines in %s"
999 modified file)))
1001 (nreverse result))))))
1003 (defun auth-source-netrc-parse-next-interesting ()
1004 "Advance to the next interesting position in the current buffer."
1005 (skip-chars-forward "\t ")
1006 ;; If we're looking at a comment or are at the end of the line, move forward
1007 (while (or (eq (char-after) ?#)
1008 (and (eolp)
1009 (not (eobp))))
1010 (forward-line 1)
1011 (skip-chars-forward "\t ")))
1013 (defun auth-source-netrc-parse-one ()
1014 "Read one thing from the current buffer."
1015 (auth-source-netrc-parse-next-interesting)
1017 (when (or (looking-at "'\\([^']*\\)'")
1018 (looking-at "\"\\([^\"]*\\)\"")
1019 (looking-at "\\([^ \t\n]+\\)"))
1020 (forward-char (length (match-string 0)))
1021 (prog1
1022 (match-string-no-properties 1)
1023 (auth-source-netrc-parse-next-interesting))))
1025 ;; with thanks to org-mode
1026 (defsubst auth-source-current-line (&optional pos)
1027 (save-excursion
1028 (and pos (goto-char pos))
1029 ;; works also in narrowed buffer, because we start at 1, not point-min
1030 (+ (if (bolp) 1 0) (count-lines 1 (point)))))
1032 (defun auth-source-netrc-parse-entries(check max)
1033 "Parse up to MAX netrc entries, passed by CHECK, from the current buffer."
1034 (let ((adder (lambda(check alist all)
1035 (when (and
1036 alist
1037 (> max (length all))
1038 (funcall check alist))
1039 (push alist all))
1040 all))
1041 item item2 all alist default)
1042 (while (setq item (auth-source-netrc-parse-one))
1043 (setq default (equal item "default"))
1044 ;; We're starting a new machine. Save the old one.
1045 (when (and alist
1046 (or default
1047 (equal item "machine")))
1048 ;; (auth-source-do-trivia
1049 ;; "auth-source-netrc-parse-entries: got entry %S" alist)
1050 (setq all (funcall adder check alist all)
1051 alist nil))
1052 ;; In default entries, we don't have a next token.
1053 ;; We store them as ("machine" . t)
1054 (if default
1055 (push (cons "machine" t) alist)
1056 ;; Not a default entry. Grab the next item.
1057 (when (setq item2 (auth-source-netrc-parse-one))
1058 ;; Did we get a "machine" value?
1059 (if (equal item2 "machine")
1060 (error
1061 "%s: Unexpected `machine' token at line %d"
1062 "auth-source-netrc-parse-entries"
1063 (auth-source-current-line))
1064 (push (cons item item2) alist)))))
1066 ;; Clean up: if there's an entry left over, use it.
1067 (when alist
1068 (setq all (funcall adder check alist all))
1069 ;; (auth-source-do-trivia
1070 ;; "auth-source-netrc-parse-entries: got2 entry %S" alist)
1072 (nreverse all)))
1074 (defvar auth-source-passphrase-alist nil)
1076 (defun auth-source-token-passphrase-callback-function (_context _key-id file)
1077 (let* ((file (file-truename file))
1078 (entry (assoc file auth-source-passphrase-alist))
1079 passphrase)
1080 ;; return the saved passphrase, calling a function if needed
1081 (or (copy-sequence (if (functionp (cdr entry))
1082 (funcall (cdr entry))
1083 (cdr entry)))
1084 (progn
1085 (unless entry
1086 (setq entry (list file))
1087 (push entry auth-source-passphrase-alist))
1088 (setq passphrase
1089 (read-passwd
1090 (format "Passphrase for %s tokens: " file)
1092 (setcdr entry (let ((p (copy-sequence passphrase)))
1093 (lambda () p)))
1094 passphrase))))
1096 (defun auth-source-epa-extract-gpg-token (secret file)
1097 "Pass either the decoded SECRET or the gpg:BASE64DATA version.
1098 FILE is the file from which we obtained this token."
1099 (when (string-match "^gpg:\\(.+\\)" secret)
1100 (setq secret (base64-decode-string (match-string 1 secret))))
1101 (let ((context (epg-make-context 'OpenPGP)))
1102 (epg-context-set-passphrase-callback
1103 context
1104 (cons #'auth-source-token-passphrase-callback-function
1105 file))
1106 (epg-decrypt-string context secret)))
1108 (defvar pp-escape-newlines)
1110 (defun auth-source-epa-make-gpg-token (secret file)
1111 (let ((context (epg-make-context 'OpenPGP))
1112 (pp-escape-newlines nil)
1113 cipher)
1114 (setf (epg-context-armor context) t)
1115 (epg-context-set-passphrase-callback
1116 context
1117 (cons #'auth-source-token-passphrase-callback-function
1118 file))
1119 (setq cipher (epg-encrypt-string context secret nil))
1120 (with-temp-buffer
1121 (insert cipher)
1122 (base64-encode-region (point-min) (point-max) t)
1123 (concat "gpg:" (buffer-substring-no-properties
1124 (point-min)
1125 (point-max))))))
1127 (defun auth-source--symbol-keyword (symbol)
1128 (intern (format ":%s" symbol)))
1130 (defun auth-source-netrc-normalize (alist filename)
1131 (mapcar (lambda (entry)
1132 (let (ret item)
1133 (while (setq item (pop entry))
1134 (let ((k (car item))
1135 (v (cdr item)))
1137 ;; apply key aliases
1138 (setq k (cond ((member k '("machine")) "host")
1139 ((member k '("login" "account")) "user")
1140 ((member k '("protocol")) "port")
1141 ((member k '("password")) "secret")
1142 (t k)))
1144 ;; send back the secret in a function (lexical binding)
1145 (when (equal k "secret")
1146 (setq v (let ((lexv v)
1147 (token-decoder nil))
1148 (when (string-match "^gpg:" lexv)
1149 ;; it's a GPG token: create a token decoder
1150 ;; which unsets itself once
1151 (setq token-decoder
1152 (lambda (val)
1153 (prog1
1154 (auth-source-epa-extract-gpg-token
1156 filename)
1157 (setq token-decoder nil)))))
1158 (lambda ()
1159 (when token-decoder
1160 (setq lexv (funcall token-decoder lexv)))
1161 lexv))))
1162 (setq ret (plist-put ret
1163 (auth-source--symbol-keyword k)
1164 v))))
1165 ret))
1166 alist))
1168 (cl-defun auth-source-netrc-search (&rest spec
1169 &key backend require create
1170 type max host user port
1171 &allow-other-keys)
1172 "Given a property list SPEC, return search matches from the :backend.
1173 See `auth-source-search' for details on SPEC."
1174 ;; just in case, check that the type is correct (null or same as the backend)
1175 (cl-assert (or (null type) (eq type (oref backend type)))
1176 t "Invalid netrc search: %s %s")
1178 (let ((results (auth-source-netrc-normalize
1179 (auth-source-netrc-parse
1180 :max max
1181 :require require
1182 :file (oref backend source)
1183 :host (or host t)
1184 :user (or user t)
1185 :port (or port t))
1186 (oref backend source))))
1188 ;; if we need to create an entry AND none were found to match
1189 (when (and create
1190 (not results))
1192 ;; create based on the spec and record the value
1193 (setq results (or
1194 ;; if the user did not want to create the entry
1195 ;; in the file, it will be returned
1196 (apply (slot-value backend 'create-function) spec)
1197 ;; if not, we do the search again without :create
1198 ;; to get the updated data.
1200 ;; the result will be returned, even if the search fails
1201 (apply #'auth-source-netrc-search
1202 (plist-put spec :create nil)))))
1203 results))
1205 (defun auth-source-netrc-element-or-first (v)
1206 (if (listp v)
1207 (nth 0 v)
1210 ;; (auth-source-search :host "nonesuch" :type 'netrc :max 1 :create t)
1211 ;; (auth-source-search :host "nonesuch" :type 'netrc :max 1 :create t :create-extra-keys '((A "default A") (B)))
1213 (cl-defun auth-source-netrc-create (&rest spec
1214 &key backend host port create
1215 &allow-other-keys)
1216 (let* ((base-required '(host user port secret))
1217 ;; we know (because of an assertion in auth-source-search) that the
1218 ;; :create parameter is either t or a list (which includes nil)
1219 (create-extra (if (eq t create) nil create))
1220 (current-data (car (auth-source-search :max 1
1221 :host host
1222 :port port)))
1223 (required (append base-required create-extra))
1224 (file (oref backend source))
1225 (add "")
1226 ;; `valist' is an alist
1227 valist
1228 ;; `artificial' will be returned if no creation is needed
1229 artificial)
1231 ;; only for base required elements (defined as function parameters):
1232 ;; fill in the valist with whatever data we may have from the search
1233 ;; we complete the first value if it's a list and use the value otherwise
1234 (dolist (br base-required)
1235 (let ((val (plist-get spec (auth-source--symbol-keyword br))))
1236 (when val
1237 (let ((br-choice (cond
1238 ;; all-accepting choice (predicate is t)
1239 ((eq t val) nil)
1240 ;; just the value otherwise
1241 (t val))))
1242 (when br-choice
1243 (auth-source--aput valist br br-choice))))))
1245 ;; for extra required elements, see if the spec includes a value for them
1246 (dolist (er create-extra)
1247 (let ((k (auth-source--symbol-keyword er))
1248 (keys (cl-loop for i below (length spec) by 2
1249 collect (nth i spec))))
1250 (when (memq k keys)
1251 (auth-source--aput valist er (plist-get spec k)))))
1253 ;; for each required element
1254 (dolist (r required)
1255 (let* ((data (auth-source--aget valist r))
1256 ;; take the first element if the data is a list
1257 (data (or (auth-source-netrc-element-or-first data)
1258 (plist-get current-data
1259 (auth-source--symbol-keyword r))))
1260 ;; this is the default to be offered
1261 (given-default (auth-source--aget
1262 auth-source-creation-defaults r))
1263 ;; the default supplementals are simple:
1264 ;; for the user, try `given-default' and then (user-login-name);
1265 ;; otherwise take `given-default'
1266 (default (cond
1267 ((and (not given-default) (eq r 'user))
1268 (user-login-name))
1269 (t given-default)))
1270 (printable-defaults (list
1271 (cons 'user
1273 (auth-source-netrc-element-or-first
1274 (auth-source--aget valist 'user))
1275 (plist-get artificial :user)
1276 "[any user]"))
1277 (cons 'host
1279 (auth-source-netrc-element-or-first
1280 (auth-source--aget valist 'host))
1281 (plist-get artificial :host)
1282 "[any host]"))
1283 (cons 'port
1285 (auth-source-netrc-element-or-first
1286 (auth-source--aget valist 'port))
1287 (plist-get artificial :port)
1288 "[any port]"))))
1289 (prompt (or (auth-source--aget auth-source-creation-prompts r)
1290 (cl-case r
1291 (secret "%p password for %u@%h: ")
1292 (user "%p user name for %h: ")
1293 (host "%p host name for user %u: ")
1294 (port "%p port for %u@%h: "))
1295 (format "Enter %s (%%u@%%h:%%p): " r)))
1296 (prompt (auth-source-format-prompt
1297 prompt
1298 `((?u ,(auth-source--aget printable-defaults 'user))
1299 (?h ,(auth-source--aget printable-defaults 'host))
1300 (?p ,(auth-source--aget printable-defaults 'port))))))
1302 ;; Store the data, prompting for the password if needed.
1303 (setq data (or data
1304 (if (eq r 'secret)
1305 ;; Special case prompt for passwords.
1306 ;; 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)))
1307 ;; TODO: or maybe leave as (setq auth-source-netrc-use-gpg-tokens 'never)
1308 (let* ((ep (format "Use GPG password tokens in %s?" file))
1309 (gpg-encrypt
1310 (cond
1311 ((eq auth-source-netrc-use-gpg-tokens 'never)
1312 'never)
1313 ((listp auth-source-netrc-use-gpg-tokens)
1314 (let ((check (copy-sequence
1315 auth-source-netrc-use-gpg-tokens))
1316 item ret)
1317 (while check
1318 (setq item (pop check))
1319 (when (or (eq (car item) t)
1320 (string-match (car item) file))
1321 (setq ret (cdr item))
1322 (setq check nil)))
1323 ret))
1324 (t 'never)))
1325 (plain (or (eval default) (read-passwd prompt))))
1326 ;; ask if we don't know what to do (in which case
1327 ;; auth-source-netrc-use-gpg-tokens must be a list)
1328 (unless gpg-encrypt
1329 (setq gpg-encrypt (if (y-or-n-p ep) 'gpg 'never))
1330 ;; TODO: save the defcustom now? or ask?
1331 (setq auth-source-netrc-use-gpg-tokens
1332 (cons `(,file ,gpg-encrypt)
1333 auth-source-netrc-use-gpg-tokens)))
1334 (if (eq gpg-encrypt 'gpg)
1335 (auth-source-epa-make-gpg-token plain file)
1336 plain))
1337 (if (stringp default)
1338 (read-string (if (string-match ": *\\'" prompt)
1339 (concat (substring prompt 0 (match-beginning 0))
1340 " (default " default "): ")
1341 (concat prompt "(default " default ") "))
1342 nil nil default)
1343 (eval default)))))
1345 (when data
1346 (setq artificial (plist-put artificial
1347 (auth-source--symbol-keyword r)
1348 (if (eq r 'secret)
1349 (let ((data data))
1350 (lambda () data))
1351 data))))
1353 ;; When r is not an empty string...
1354 (when (and (stringp data)
1355 (< 0 (length data)))
1356 ;; this function is not strictly necessary but I think it
1357 ;; makes the code clearer -tzz
1358 (let ((printer (lambda ()
1359 ;; append the key (the symbol name of r)
1360 ;; and the value in r
1361 (format "%s%s %s"
1362 ;; prepend a space
1363 (if (zerop (length add)) "" " ")
1364 ;; remap auth-source tokens to netrc
1365 (cl-case r
1366 (user "login")
1367 (host "machine")
1368 (secret "password")
1369 (port "port") ; redundant but clearer
1370 (t (symbol-name r)))
1371 (if (string-match "[\"# ]" data)
1372 (format "%S" data)
1373 data)))))
1374 (setq add (concat add (funcall printer)))))))
1376 (plist-put
1377 artificial
1378 :save-function
1379 (let ((file file)
1380 (add add))
1381 (lambda () (auth-source-netrc-saver file add))))
1383 (list artificial)))
1385 (defun auth-source-netrc-saver (file add)
1386 "Save a line ADD in FILE, prompting along the way.
1387 Respects `auth-source-save-behavior'. Uses
1388 `auth-source-netrc-cache' to avoid prompting more than once."
1389 (let* ((key (format "%s %s" file (rfc2104-hash 'md5 64 16 file add)))
1390 (cached (assoc key auth-source-netrc-cache)))
1392 (if cached
1393 (auth-source-do-trivia
1394 "auth-source-netrc-saver: found previous run for key %s, returning"
1395 key)
1396 (with-temp-buffer
1397 (when (file-exists-p file)
1398 (insert-file-contents file))
1399 (when auth-source-gpg-encrypt-to
1400 ;; (see bug#7487) making `epa-file-encrypt-to' local to
1401 ;; this buffer lets epa-file skip the key selection query
1402 ;; (see the `local-variable-p' check in
1403 ;; `epa-file-write-region').
1404 (unless (local-variable-p 'epa-file-encrypt-to (current-buffer))
1405 (make-local-variable 'epa-file-encrypt-to))
1406 (if (listp auth-source-gpg-encrypt-to)
1407 (setq epa-file-encrypt-to auth-source-gpg-encrypt-to)))
1408 ;; we want the new data to be found first, so insert at beginning
1409 (goto-char (point-min))
1411 ;; Ask AFTER we've successfully opened the file.
1412 (let ((prompt (format "Save auth info to file %s? " file))
1413 (done (not (eq auth-source-save-behavior 'ask)))
1414 (bufname "*auth-source Help*")
1416 (while (not done)
1417 (setq k (auth-source-read-char-choice prompt '(?y ?n ?N ?e ??)))
1418 (cl-case k
1419 (?y (setq done t))
1420 (?? (save-excursion
1421 (with-output-to-temp-buffer bufname
1422 (princ
1423 (concat "(y)es, save\n"
1424 "(n)o but use the info\n"
1425 "(N)o and don't ask to save again\n"
1426 "(e)dit the line\n"
1427 "(?) for help as you can see.\n"))
1428 ;; Why? Doesn't with-output-to-temp-buffer already do
1429 ;; the exact same thing anyway? --Stef
1430 (set-buffer standard-output)
1431 (help-mode))))
1432 (?n (setq add ""
1433 done t))
1435 (setq add ""
1436 done t)
1437 (customize-save-variable 'auth-source-save-behavior nil))
1438 (?e (setq add (read-string "Line to add: " add)))
1439 (t nil)))
1441 (when (get-buffer-window bufname)
1442 (delete-window (get-buffer-window bufname)))
1444 ;; Make sure the info is not saved.
1445 (when (null auth-source-save-behavior)
1446 (setq add ""))
1448 (when (< 0 (length add))
1449 (progn
1450 (unless (bolp)
1451 (insert "\n"))
1452 (insert add "\n")
1453 (write-region (point-min) (point-max) file nil 'silent)
1454 ;; Make the .authinfo file non-world-readable.
1455 (set-file-modes file #o600)
1456 (auth-source-do-debug
1457 "auth-source-netrc-create: wrote 1 new line to %s"
1458 file)
1459 (message "Saved new authentication information to %s" file)
1460 nil))))
1461 (auth-source--aput auth-source-netrc-cache key "ran"))))
1463 ;;; Backend specific parsing: Secrets API backend
1465 (defun auth-source-secrets-listify-pattern (pattern)
1466 "Convert a pattern with lists to a list of string patterns.
1468 auth-source patterns can have values of the form :foo (\"bar\"
1469 \"qux\"), which means to match any secret with :foo equal to
1470 \"bar\" or :foo equal to \"qux\". The secrets backend supports
1471 only string values for patterns, so this routine returns a list
1472 of patterns that is equivalent to the single original pattern
1473 when interpreted such that if a secret matches any pattern in the
1474 list, it matches the original pattern."
1475 (if (null pattern)
1476 '(nil)
1477 (let* ((key (pop pattern))
1478 (value (pop pattern))
1479 (tails (auth-source-secrets-listify-pattern pattern))
1480 (heads (if (stringp value)
1481 (list (list key value))
1482 (mapcar (lambda (v) (list key v)) value))))
1483 (cl-loop for h in heads
1484 nconc (cl-loop for tl in tails collect (append h tl))))))
1486 (cl-defun auth-source-secrets-search (&rest spec
1487 &key backend create delete label max
1488 &allow-other-keys)
1489 "Search the Secrets API; spec is like `auth-source'.
1491 The :label key specifies the item's label. It is the only key
1492 that can specify a substring. Any :label value besides a string
1493 will allow any label.
1495 All other search keys must match exactly. If you need substring
1496 matching, do a wider search and narrow it down yourself.
1498 You'll get back all the properties of the token as a plist.
1500 Here's an example that looks for the first item in the `Login'
1501 Secrets collection:
1503 (let ((auth-sources \\='(\"secrets:Login\")))
1504 (auth-source-search :max 1))
1506 Here's another that looks for the first item in the `Login'
1507 Secrets collection whose label contains `gnus':
1509 (let ((auth-sources \\='(\"secrets:Login\")))
1510 (auth-source-search :max 1 :label \"gnus\"))
1512 And this one looks for the first item in the `Login' Secrets
1513 collection that's a Google Chrome entry for the git.gnus.org site
1514 authentication tokens:
1516 (let ((auth-sources \\='(\"secrets:Login\")))
1517 (auth-source-search :max 1 :signon_realm \"https://git.gnus.org/Git\"))
1520 ;; TODO
1521 ;; (secrets-delete-item coll elt)
1522 (cl-assert (not delete) nil
1523 "The Secrets API auth-source backend doesn't support deletion yet")
1525 (let* ((coll (oref backend source))
1526 (max (or max 5000)) ; sanity check: default to stop at 5K
1527 (ignored-keys '(:create :delete :max :backend :label :require :type))
1528 (search-keys (cl-loop for i below (length spec) by 2
1529 unless (memq (nth i spec) ignored-keys)
1530 collect (nth i spec)))
1531 ;; build a search spec without the ignored keys
1532 ;; if a search key is nil or t (match anything), we skip it
1533 (search-specs (auth-source-secrets-listify-pattern
1534 (apply #'append (mapcar
1535 (lambda (k)
1536 (if (or (null (plist-get spec k))
1537 (eq t (plist-get spec k)))
1539 (list k (plist-get spec k))))
1540 search-keys))))
1541 ;; needed keys (always including host, login, port, and secret)
1542 (returned-keys (delete-dups (append
1543 '(:host :login :port :secret)
1544 search-keys)))
1545 (items
1546 (cl-loop
1547 for search-spec in search-specs
1548 nconc
1549 (cl-loop for item in (apply #'secrets-search-items coll search-spec)
1550 unless (and (stringp label)
1551 (not (string-match label item)))
1552 collect item)))
1553 ;; TODO: respect max in `secrets-search-items', not after the fact
1554 (items (butlast items (- (length items) max)))
1555 ;; convert the item name to a full plist
1556 (items (mapcar (lambda (item)
1557 (append
1558 ;; make an entry for the secret (password) element
1559 (list
1560 :secret
1561 (let ((v (secrets-get-secret coll item)))
1562 (lambda () v)))
1563 ;; rewrite the entry from ((k1 v1) (k2 v2)) to plist
1564 (apply #'append
1565 (mapcar (lambda (entry)
1566 (list (car entry) (cdr entry)))
1567 (secrets-get-attributes coll item)))))
1568 items))
1569 ;; ensure each item has each key in `returned-keys'
1570 (items (mapcar (lambda (plist)
1571 (append
1572 (apply #'append
1573 (mapcar (lambda (req)
1574 (if (plist-get plist req)
1576 (list req nil)))
1577 returned-keys))
1578 plist))
1579 items)))
1580 (cond
1581 ;; if we need to create an entry AND none were found to match
1582 ((and create
1583 (not items))
1585 ;; create based on the spec and record the value
1586 (setq items (or
1587 ;; if the user did not want to create the entry
1588 ;; in the file, it will be returned
1589 (apply (slot-value backend 'create-function) spec)
1590 ;; if not, we do the search again without :create
1591 ;; to get the updated data.
1593 ;; the result will be returned, even if the search fails
1594 (apply #'auth-source-secrets-search
1595 (plist-put spec :create nil))))))
1596 items))
1598 (cl-defun auth-source-secrets-create (&rest spec
1599 &key backend host port create
1600 &allow-other-keys)
1601 (let* ((base-required '(host user port secret label))
1602 ;; we know (because of an assertion in auth-source-search) that the
1603 ;; :create parameter is either t or a list (which includes nil)
1604 (create-extra (if (eq t create) nil create))
1605 (current-data (car (auth-source-search :max 1
1606 :host host
1607 :port port)))
1608 (required (append base-required create-extra))
1609 (collection (oref backend source))
1610 ;; `args' are the arguments for `secrets-create-item'.
1611 args
1612 ;; `valist' is an alist
1613 valist
1614 ;; `artificial' will be returned if no creation is needed
1615 artificial)
1617 ;; only for base required elements (defined as function parameters):
1618 ;; fill in the valist with whatever data we may have from the search
1619 ;; we complete the first value if it's a list and use the value otherwise
1620 (dolist (br base-required)
1621 (let ((val (plist-get spec (auth-source--symbol-keyword br))))
1622 (when val
1623 (let ((br-choice (cond
1624 ;; all-accepting choice (predicate is t)
1625 ((eq t val) nil)
1626 ;; just the value otherwise
1627 (t val))))
1628 (when br-choice
1629 (auth-source--aput valist br br-choice))))))
1631 ;; for extra required elements, see if the spec includes a value for them
1632 (dolist (er create-extra)
1633 (let ((k (auth-source--symbol-keyword er))
1634 (keys (cl-loop for i below (length spec) by 2
1635 collect (nth i spec))))
1636 (when (memq k keys)
1637 (auth-source--aput valist er (plist-get spec k)))))
1639 ;; for each required element
1640 (dolist (r required)
1641 (let* ((data (auth-source--aget valist r))
1642 ;; take the first element if the data is a list
1643 (data (or (auth-source-netrc-element-or-first data)
1644 (plist-get current-data
1645 (auth-source--symbol-keyword r))))
1646 ;; this is the default to be offered
1647 (given-default (auth-source--aget
1648 auth-source-creation-defaults r))
1649 ;; the default supplementals are simple:
1650 ;; for the user, try `given-default' and then (user-login-name);
1651 ;; for the label, try `given-default' and then user@host;
1652 ;; otherwise take `given-default'
1653 (default (cond
1654 ((and (not given-default) (eq r 'user))
1655 (user-login-name))
1656 ((and (not given-default) (eq r 'label))
1657 (format "%s@%s"
1658 (or (auth-source-netrc-element-or-first
1659 (auth-source--aget valist 'user))
1660 (plist-get artificial :user))
1661 (or (auth-source-netrc-element-or-first
1662 (auth-source--aget valist 'host))
1663 (plist-get artificial :host))))
1664 (t given-default)))
1665 (printable-defaults (list
1666 (cons 'user
1668 (auth-source-netrc-element-or-first
1669 (auth-source--aget valist 'user))
1670 (plist-get artificial :user)
1671 "[any user]"))
1672 (cons 'host
1674 (auth-source-netrc-element-or-first
1675 (auth-source--aget valist 'host))
1676 (plist-get artificial :host)
1677 "[any host]"))
1678 (cons 'port
1680 (auth-source-netrc-element-or-first
1681 (auth-source--aget valist 'port))
1682 (plist-get artificial :port)
1683 "[any port]"))
1684 (cons 'label
1686 (auth-source-netrc-element-or-first
1687 (auth-source--aget valist 'label))
1688 (plist-get artificial :label)
1689 "[any label]"))))
1690 (prompt (or (auth-source--aget auth-source-creation-prompts r)
1691 (cl-case r
1692 (secret "%p password for %u@%h: ")
1693 (user "%p user name for %h: ")
1694 (host "%p host name for user %u: ")
1695 (port "%p port for %u@%h: ")
1696 (label "Enter label for %u@%h: "))
1697 (format "Enter %s (%%u@%%h:%%p): " r)))
1698 (prompt (auth-source-format-prompt
1699 prompt
1700 `((?u ,(auth-source--aget printable-defaults 'user))
1701 (?h ,(auth-source--aget printable-defaults 'host))
1702 (?p ,(auth-source--aget printable-defaults 'port))))))
1704 ;; Store the data, prompting for the password if needed.
1705 (setq data (or data
1706 (if (eq r 'secret)
1707 (or (eval default) (read-passwd prompt))
1708 (if (stringp default)
1709 (read-string (if (string-match ": *\\'" prompt)
1710 (concat (substring prompt 0 (match-beginning 0))
1711 " (default " default "): ")
1712 (concat prompt "(default " default ") "))
1713 nil nil default)
1714 (eval default)))))
1716 (when data
1717 (setq artificial (plist-put artificial
1718 (auth-source--symbol-keyword r)
1719 (if (eq r 'secret)
1720 (let ((data data))
1721 (lambda () data))
1722 data))))
1724 ;; When r is not an empty string...
1725 (when (and (stringp data)
1726 (< 0 (length data))
1727 (not (member r '(secret label))))
1728 ;; append the key (the symbol name of r)
1729 ;; and the value in r
1730 (setq args (append args (list (auth-source--symbol-keyword r) data))))))
1732 (plist-put
1733 artificial
1734 :save-function
1735 (let* ((collection collection)
1736 (item (plist-get artificial :label))
1737 (secret (plist-get artificial :secret))
1738 (secret (if (functionp secret) (funcall secret) secret)))
1739 (lambda ()
1740 (auth-source-secrets-saver collection item secret args))))
1742 (list artificial)))
1744 (defun auth-source-secrets-saver (collection item secret args)
1745 "Wrapper around `secrets-create-item', prompting along the way.
1746 Respects `auth-source-save-behavior'."
1747 (let ((prompt (format "Save auth info to secrets collection %s? " collection))
1748 (done (not (eq auth-source-save-behavior 'ask)))
1749 (doit (eq auth-source-save-behavior t))
1750 (bufname "*auth-source Help*")
1752 (while (not done)
1753 (setq k (auth-source-read-char-choice prompt '(?y ?n ?N ??)))
1754 (cl-case k
1755 (?y (setq done t doit t))
1756 (?? (save-excursion
1757 (with-output-to-temp-buffer bufname
1758 (princ
1759 (concat "(y)es, save\n"
1760 "(n)o but use the info\n"
1761 "(N)o and don't ask to save again\n"
1762 "(?) for help as you can see.\n"))
1763 ;; Why? Doesn't with-output-to-temp-buffer already do
1764 ;; the exact same thing anyway? --Stef
1765 (set-buffer standard-output)
1766 (help-mode))))
1767 (?n (setq done t doit nil))
1768 (?N (setq done t doit nil)
1769 (customize-save-variable 'auth-source-save-behavior nil))
1770 (t nil)))
1772 (when doit
1773 (progn
1774 (auth-source-do-debug
1775 "secrets-create-item: wrote 1 new item to %s" collection)
1776 (message "Saved new authentication information to %s" collection)
1777 (apply 'secrets-create-item collection item secret args)))))
1779 ;;; Backend specific parsing: Mac OS Keychain (using /usr/bin/security) backend
1781 (cl-defun auth-source-macos-keychain-search (&rest spec
1782 &key backend create delete type max
1783 &allow-other-keys)
1784 "Search the macOS Keychain; spec is like `auth-source'.
1786 All search keys must match exactly. If you need substring
1787 matching, do a wider search and narrow it down yourself.
1789 You'll get back all the properties of the token as a plist.
1791 The :type key is either `macos-keychain-internet' or
1792 `macos-keychain-generic'.
1794 For the internet keychain type, the :label key searches the
1795 item's labels (\"-l LABEL\" passed to \"/usr/bin/security\").
1796 Similarly, :host maps to \"-s HOST\", :user maps to \"-a USER\",
1797 and :port maps to \"-P PORT\" or \"-r PROT\"
1798 \(note PROT has to be a 4-character string).
1800 For the generic keychain type, the :label key searches the item's
1801 labels (\"-l LABEL\" passed to \"/usr/bin/security\").
1802 Similarly, :host maps to \"-c HOST\" (the \"creator\" keychain
1803 field), :user maps to \"-a USER\", and :port maps to \"-s PORT\".
1805 Here's an example that looks for the first item in the default
1806 generic macOS Keychain:
1808 (let ((auth-sources \\='(macos-keychain-generic)))
1809 (auth-source-search :max 1)
1811 Here's another that looks for the first item in the internet
1812 macOS Keychain collection whose label is `gnus':
1814 (let ((auth-sources \\='(macos-keychain-internet)))
1815 (auth-source-search :max 1 :label \"gnus\")
1817 And this one looks for the first item in the internet keychain
1818 entries for git.gnus.org:
1820 (let ((auth-sources \\='(macos-keychain-internet\")))
1821 (auth-source-search :max 1 :host \"git.gnus.org\"))
1823 ;; TODO
1824 (cl-assert (not create) nil
1825 "The macOS Keychain auth-source backend doesn't support creation yet")
1826 ;; TODO
1827 ;; (macos-keychain-delete-item coll elt)
1828 (cl-assert (not delete) nil
1829 "The macOS Keychain auth-source backend doesn't support deletion yet")
1831 (let* ((coll (oref backend source))
1832 (max (or max 5000)) ; sanity check: default to stop at 5K
1833 ;; Filter out ignored keys from the spec
1834 (ignored-keys '(:create :delete :max :backend :label :host :port))
1835 ;; Build a search spec without the ignored keys
1836 ;; FIXME make this loop a function? it's used in at least 3 places
1837 (search-keys (cl-loop for i below (length spec) by 2
1838 unless (memq (nth i spec) ignored-keys)
1839 collect (nth i spec)))
1840 ;; If a search key value is nil or t (match anything), we skip it
1841 (search-spec (apply #'append (mapcar
1842 (lambda (k)
1843 (if (or (null (plist-get spec k))
1844 (eq t (plist-get spec k)))
1846 (list k (plist-get spec k))))
1847 search-keys)))
1848 ;; needed keys (always including host, login, port, and secret)
1849 (returned-keys (delete-dups (append
1850 '(:host :login :port :secret)
1851 search-keys)))
1852 ;; Extract host and port from spec
1853 (hosts (plist-get spec :host))
1854 (hosts (if (and hosts (listp hosts)) hosts `(,hosts)))
1855 (ports (plist-get spec :port))
1856 (ports (if (and ports (listp ports)) ports `(,ports)))
1857 ;; Loop through all combinations of host/port and pass each of these to
1858 ;; auth-source-macos-keychain-search-items
1859 (items (catch 'match
1860 (dolist (host hosts)
1861 (dolist (port ports)
1862 (let* ((port (if port (format "%S" port)))
1863 (items (apply #'auth-source-macos-keychain-search-items
1864 coll
1865 type
1867 host port
1868 search-spec)))
1869 (when items
1870 (throw 'match items)))))))
1872 ;; ensure each item has each key in `returned-keys'
1873 (items (mapcar (lambda (plist)
1874 (append
1875 (apply #'append
1876 (mapcar (lambda (req)
1877 (if (plist-get plist req)
1879 (list req nil)))
1880 returned-keys))
1881 plist))
1882 items)))
1883 items))
1886 (defun auth-source--decode-octal-string (string)
1887 "Convert octal string to utf-8 string. E.g: 'a\134b' to 'a\b'"
1888 (let ((list (string-to-list string))
1889 (size (length string)))
1890 (decode-coding-string
1891 (apply #'unibyte-string
1892 (cl-loop for i = 0 then (+ i (if (eq (nth i list) ?\\) 4 1))
1893 for var = (nth i list)
1894 while (< i size)
1895 if (eq var ?\\)
1896 collect (string-to-number
1897 (concat (cl-subseq list (+ i 1) (+ i 4))) 8)
1898 else
1899 collect var))
1900 'utf-8)))
1902 (cl-defun auth-source-macos-keychain-search-items (coll _type _max host port
1903 &key label type user
1904 &allow-other-keys)
1905 (let* ((keychain-generic (eq type 'macos-keychain-generic))
1906 (args `(,(if keychain-generic
1907 "find-generic-password"
1908 "find-internet-password")
1909 "-g"))
1910 (ret (list :type type)))
1911 (when label
1912 (setq args (append args (list "-l" label))))
1913 (when host
1914 (setq args (append args (list (if keychain-generic "-c" "-s") host))))
1915 (when user
1916 (setq args (append args (list "-a" user))))
1918 (when port
1919 (if keychain-generic
1920 (setq args (append args (list "-s" port)))
1921 (setq args (append args (list
1922 (if (string-match "[0-9]+" port) "-P" "-r")
1923 port)))))
1925 (unless (equal coll "default")
1926 (setq args (append args (list coll))))
1928 (with-temp-buffer
1929 (apply #'call-process "/usr/bin/security" nil t nil args)
1930 (goto-char (point-min))
1931 (while (not (eobp))
1932 (cond
1933 ((looking-at "^password: \\(?:0x[0-9A-F]+\\)? *\"\\(.+\\)\"")
1934 (setq ret (auth-source-macos-keychain-result-append
1936 keychain-generic
1937 "secret"
1938 (let ((v (auth-source--decode-octal-string
1939 (match-string 1))))
1940 (lambda () v)))))
1941 ;; TODO: check if this is really the label
1942 ;; match 0x00000007 <blob>="AppleID"
1943 ((looking-at
1944 "^[ ]+0x00000007 <blob>=\\(?:0x[0-9A-F]+\\)? *\"\\(.+\\)\"")
1945 (setq ret (auth-source-macos-keychain-result-append
1947 keychain-generic
1948 "label"
1949 (auth-source--decode-octal-string (match-string 1)))))
1950 ;; match "crtr"<uint32>="aapl"
1951 ;; match "svce"<blob>="AppleID"
1952 ((looking-at
1953 "^[ ]+\"\\([a-z]+\\)\"[^=]+=\\(?:0x[0-9A-F]+\\)? *\"\\(.+\\)\"")
1954 (setq ret (auth-source-macos-keychain-result-append
1956 keychain-generic
1957 (auth-source--decode-octal-string (match-string 1))
1958 (auth-source--decode-octal-string (match-string 2))))))
1959 (forward-line)))
1960 ;; return `ret' iff it has the :secret key
1961 (and (plist-get ret :secret) (list ret))))
1963 (defun auth-source-macos-keychain-result-append (result generic k v)
1964 (push v result)
1965 (push (auth-source--symbol-keyword
1966 (cond
1967 ((equal k "acct") "user")
1968 ;; for generic keychains, creator is host, service is port
1969 ((and generic (equal k "crtr")) "host")
1970 ((and generic (equal k "svce")) "port")
1971 ;; for internet keychains, protocol is port, server is host
1972 ((and (not generic) (equal k "ptcl")) "port")
1973 ((and (not generic) (equal k "srvr")) "host")
1974 (t k)))
1975 result))
1977 (defun auth-source-macos-keychain-create (&rest spec)
1978 ;; TODO
1979 (debug spec))
1981 ;;; Backend specific parsing: PLSTORE backend
1983 (cl-defun auth-source-plstore-search (&rest spec
1984 &key backend create delete max
1985 &allow-other-keys)
1986 "Search the PLSTORE; spec is like `auth-source'."
1987 (let* ((store (oref backend data))
1988 (max (or max 5000)) ; sanity check: default to stop at 5K
1989 (ignored-keys '(:create :delete :max :backend :label :require :type))
1990 (search-keys (cl-loop for i below (length spec) by 2
1991 unless (memq (nth i spec) ignored-keys)
1992 collect (nth i spec)))
1993 ;; build a search spec without the ignored keys
1994 ;; if a search key is nil or t (match anything), we skip it
1995 (search-spec (apply #'append (mapcar
1996 (lambda (k)
1997 (let ((v (plist-get spec k)))
1998 (if (or (null v)
1999 (eq t v))
2001 (if (stringp v)
2002 (setq v (list v)))
2003 (list k v))))
2004 search-keys)))
2005 ;; needed keys (always including host, login, port, and secret)
2006 (returned-keys (delete-dups (append
2007 '(:host :login :port :secret)
2008 search-keys)))
2009 (items (plstore-find store search-spec))
2010 (item-names (mapcar #'car items))
2011 (items (butlast items (- (length items) max)))
2012 ;; convert the item to a full plist
2013 (items (mapcar (lambda (item)
2014 (let* ((plist (copy-tree (cdr item)))
2015 (secret (plist-member plist :secret)))
2016 (if secret
2017 (setcar
2018 (cdr secret)
2019 (let ((v (car (cdr secret))))
2020 (lambda () v))))
2021 plist))
2022 items))
2023 ;; ensure each item has each key in `returned-keys'
2024 (items (mapcar (lambda (plist)
2025 (append
2026 (apply #'append
2027 (mapcar (lambda (req)
2028 (if (plist-get plist req)
2030 (list req nil)))
2031 returned-keys))
2032 plist))
2033 items)))
2034 (cond
2035 ;; if we need to create an entry AND none were found to match
2036 ((and create
2037 (not items))
2039 ;; create based on the spec and record the value
2040 (setq items (or
2041 ;; if the user did not want to create the entry
2042 ;; in the file, it will be returned
2043 (apply (slot-value backend 'create-function) spec)
2044 ;; if not, we do the search again without :create
2045 ;; to get the updated data.
2047 ;; the result will be returned, even if the search fails
2048 (apply #'auth-source-plstore-search
2049 (plist-put spec :create nil)))))
2050 ((and delete
2051 item-names)
2052 (dolist (item-name item-names)
2053 (plstore-delete store item-name))
2054 (plstore-save store)))
2055 items))
2057 (cl-defun auth-source-plstore-create (&rest spec
2058 &key backend host port create
2059 &allow-other-keys)
2060 (let* ((base-required '(host user port secret))
2061 (base-secret '(secret))
2062 ;; we know (because of an assertion in auth-source-search) that the
2063 ;; :create parameter is either t or a list (which includes nil)
2064 (create-extra (if (eq t create) nil create))
2065 (current-data (car (auth-source-search :max 1
2066 :host host
2067 :port port)))
2068 (required (append base-required create-extra))
2069 ;; `valist' is an alist
2070 valist
2071 ;; `artificial' will be returned if no creation is needed
2072 artificial
2073 secret-artificial)
2075 ;; only for base required elements (defined as function parameters):
2076 ;; fill in the valist with whatever data we may have from the search
2077 ;; we complete the first value if it's a list and use the value otherwise
2078 (dolist (br base-required)
2079 (let ((val (plist-get spec (auth-source--symbol-keyword br))))
2080 (when val
2081 (let ((br-choice (cond
2082 ;; all-accepting choice (predicate is t)
2083 ((eq t val) nil)
2084 ;; just the value otherwise
2085 (t val))))
2086 (when br-choice
2087 (auth-source--aput valist br br-choice))))))
2089 ;; for extra required elements, see if the spec includes a value for them
2090 (dolist (er create-extra)
2091 (let ((k (auth-source--symbol-keyword er))
2092 (keys (cl-loop for i below (length spec) by 2
2093 collect (nth i spec))))
2094 (when (memq k keys)
2095 (auth-source--aput valist er (plist-get spec k)))))
2097 ;; for each required element
2098 (dolist (r required)
2099 (let* ((data (auth-source--aget valist r))
2100 ;; take the first element if the data is a list
2101 (data (or (auth-source-netrc-element-or-first data)
2102 (plist-get current-data
2103 (auth-source--symbol-keyword r))))
2104 ;; this is the default to be offered
2105 (given-default (auth-source--aget
2106 auth-source-creation-defaults r))
2107 ;; the default supplementals are simple:
2108 ;; for the user, try `given-default' and then (user-login-name);
2109 ;; otherwise take `given-default'
2110 (default (cond
2111 ((and (not given-default) (eq r 'user))
2112 (user-login-name))
2113 (t given-default)))
2114 (printable-defaults (list
2115 (cons 'user
2117 (auth-source-netrc-element-or-first
2118 (auth-source--aget valist 'user))
2119 (plist-get artificial :user)
2120 "[any user]"))
2121 (cons 'host
2123 (auth-source-netrc-element-or-first
2124 (auth-source--aget valist 'host))
2125 (plist-get artificial :host)
2126 "[any host]"))
2127 (cons 'port
2129 (auth-source-netrc-element-or-first
2130 (auth-source--aget valist 'port))
2131 (plist-get artificial :port)
2132 "[any port]"))))
2133 (prompt (or (auth-source--aget auth-source-creation-prompts r)
2134 (cl-case r
2135 (secret "%p password for %u@%h: ")
2136 (user "%p user name for %h: ")
2137 (host "%p host name for user %u: ")
2138 (port "%p port for %u@%h: "))
2139 (format "Enter %s (%%u@%%h:%%p): " r)))
2140 (prompt (auth-source-format-prompt
2141 prompt
2142 `((?u ,(auth-source--aget printable-defaults 'user))
2143 (?h ,(auth-source--aget printable-defaults 'host))
2144 (?p ,(auth-source--aget printable-defaults 'port))))))
2146 ;; Store the data, prompting for the password if needed.
2147 (setq data (or data
2148 (if (eq r 'secret)
2149 (or (eval default) (read-passwd prompt))
2150 (if (stringp default)
2151 (read-string
2152 (if (string-match ": *\\'" prompt)
2153 (concat (substring prompt 0 (match-beginning 0))
2154 " (default " default "): ")
2155 (concat prompt "(default " default ") "))
2156 nil nil default)
2157 (eval default)))))
2159 (when data
2160 (if (member r base-secret)
2161 (setq secret-artificial
2162 (plist-put secret-artificial
2163 (auth-source--symbol-keyword r)
2164 data))
2165 (setq artificial (plist-put artificial
2166 (auth-source--symbol-keyword r)
2167 data))))))
2168 (plstore-put (oref backend data)
2169 (sha1 (format "%s@%s:%s"
2170 (plist-get artificial :user)
2171 (plist-get artificial :host)
2172 (plist-get artificial :port)))
2173 artificial secret-artificial)
2174 (if (y-or-n-p (format "Save auth info to file %s? "
2175 (plstore-get-file (oref backend data))))
2176 (plstore-save (oref backend data)))))
2178 ;;; Backend specific parsing: JSON backend
2179 ;;; (auth-source-search :max 1 :machine "imap.gmail.com")
2180 ;;; (auth-source-search :max 1 :host '("my-gmail" "imap.gmail.com") :port '(993 "imaps" "imap" "993" "143") :user nil :require '(:user :secret))
2182 (defun auth-source-json-check (host user port require item)
2183 (and item
2184 (auth-source-search-collection
2185 (or host t)
2187 (plist-get item :machine)
2188 (plist-get item :host)
2190 (auth-source-search-collection
2191 (or user t)
2193 (plist-get item :login)
2194 (plist-get item :account)
2195 (plist-get item :user)
2197 (auth-source-search-collection
2198 (or port t)
2200 (plist-get item :port)
2201 (plist-get item :protocol)
2204 ;; the required list of keys is nil, or
2205 (null require)
2206 ;; every element of require is in
2207 (cl-loop for req in require
2208 always (plist-get item req)))))
2210 (cl-defun auth-source-json-search (&rest spec
2211 &key backend require
2212 type max host user port
2213 &allow-other-keys)
2214 "Given a property list SPEC, return search matches from the :backend.
2215 See `auth-source-search' for details on SPEC."
2216 ;; just in case, check that the type is correct (null or same as the backend)
2217 (cl-assert (or (null type) (eq type (oref backend type)))
2218 t "Invalid JSON search: %s %s")
2220 ;; Hide the secrets early to avoid accidental exposure.
2221 (let* ((jdata
2222 (mapcar (lambda (entry)
2223 (let (ret)
2224 (while entry
2225 (let* ((item (pop entry))
2226 (k (auth-source--symbol-keyword (car item)))
2227 (v (cdr item)))
2228 (setq k (cond ((memq k '(:machine)) :host)
2229 ((memq k '(:login :account)) :user)
2230 ((memq k '(:protocol)) :port)
2231 ((memq k '(:password)) :secret)
2232 (t k)))
2233 ;; send back the secret in a function (lexical binding)
2234 (when (eq k :secret)
2235 (setq v (let ((lexv v))
2236 (lambda () lexv))))
2237 (setq ret (plist-put ret k v))))
2238 ret))
2239 (json-read-file (oref backend source))))
2240 (max (or max 5000)) ; sanity check: default to stop at 5K
2241 all)
2242 (dolist (item jdata)
2243 (when (and item
2244 (> max (length all))
2245 (auth-source-json-check host user port require item))
2246 (push item all)))
2247 (nreverse all)))
2249 ;;; older API
2251 ;; (auth-source-user-or-password '("login" "password") "imap.myhost.com" t "tzz")
2253 ;; deprecate the old interface
2254 (make-obsolete 'auth-source-user-or-password
2255 'auth-source-search "Emacs 24.1")
2256 (make-obsolete 'auth-source-forget-user-or-password
2257 'auth-source-forget "Emacs 24.1")
2259 (defun auth-source-user-or-password
2260 (mode host port &optional username create-missing delete-existing)
2261 "Find MODE (string or list of strings) matching HOST and PORT.
2263 DEPRECATED in favor of `auth-source-search'!
2265 USERNAME is optional and will be used as \"login\" in a search
2266 across the Secret Service API (see secrets.el) if the resulting
2267 items don't have a username. This means that if you search for
2268 username \"joe\" and it matches an item but the item doesn't have
2269 a :user attribute, the username \"joe\" will be returned.
2271 A non nil DELETE-EXISTING means deleting any matching password
2272 entry in the respective sources. This is useful only when
2273 CREATE-MISSING is non nil as well; the intended use case is to
2274 remove wrong password entries.
2276 If no matching entry is found, and CREATE-MISSING is non nil,
2277 the password will be retrieved interactively, and it will be
2278 stored in the password database which matches best (see
2279 `auth-sources').
2281 MODE can be \"login\" or \"password\"."
2282 (auth-source-do-debug
2283 "auth-source-user-or-password: DEPRECATED get %s for %s (%s) + user=%s"
2284 mode host port username)
2286 (let* ((listy (listp mode))
2287 (mode (if listy mode (list mode)))
2288 ;; (cname (if username
2289 ;; (format "%s %s:%s %s" mode host port username)
2290 ;; (format "%s %s:%s" mode host port)))
2291 (search (list :host host :port port))
2292 (search (if username (append search (list :user username)) search))
2293 (search (if create-missing
2294 (append search (list :create t))
2295 search))
2296 (search (if delete-existing
2297 (append search (list :delete t))
2298 search))
2299 ;; (found (if (not delete-existing)
2300 ;; (gethash cname auth-source-cache)
2301 ;; (remhash cname auth-source-cache)
2302 ;; nil)))
2303 (found nil))
2304 (if found
2305 (progn
2306 (auth-source-do-debug
2307 "auth-source-user-or-password: DEPRECATED cached %s=%s for %s (%s) + %s"
2308 mode
2309 ;; don't show the password
2310 (if (and (member "password" mode) t)
2311 "SECRET"
2312 found)
2313 host port username)
2314 found) ; return the found data
2315 ;; else, if not found, search with a max of 1
2316 (let ((choice (nth 0 (apply #'auth-source-search
2317 (append '(:max 1) search)))))
2318 (when choice
2319 (dolist (m mode)
2320 (cond
2321 ((equal "password" m)
2322 (push (if (plist-get choice :secret)
2323 (funcall (plist-get choice :secret))
2324 nil) found))
2325 ((equal "login" m)
2326 (push (plist-get choice :user) found)))))
2327 (setq found (nreverse found))
2328 (setq found (if listy found (car-safe found)))))
2330 found))
2332 (defun auth-source-user-and-password (host &optional user)
2333 (let* ((auth-info (car
2334 (if user
2335 (auth-source-search
2336 :host host
2337 :user user
2338 :max 1
2339 :require '(:user :secret)
2340 :create nil)
2341 (auth-source-search
2342 :host host
2343 :max 1
2344 :require '(:user :secret)
2345 :create nil))))
2346 (user (plist-get auth-info :user))
2347 (password (plist-get auth-info :secret)))
2348 (when (functionp password)
2349 (setq password (funcall password)))
2350 (list user password auth-info)))
2352 (provide 'auth-source)
2354 ;;; auth-source.el ends here