(gnus-blocked-images): Clarify privacy implications
[emacs.git] / lisp / auth-source.el
blobabff0def95f146fb2ecd7b4b7c867b365f0d076e
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 (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 (nth 5 (file-attributes file))))
960 (progn
961 (auth-source-do-trivia
962 "auth-source-netrc-parse: using CACHED file data for %s"
963 file)
964 (insert (funcall cached-secrets)))
965 (insert-file-contents file)
966 ;; cache all netrc files (used to be just .gpg files)
967 ;; Store the contents of the file heavily encrypted in memory.
968 ;; (note for the irony-impaired: they are just obfuscated)
969 (auth-source--aput
970 auth-source-netrc-cache file
971 (list :mtime (nth 5 (file-attributes file))
972 :secret (let ((v (mapcar #'1+ (buffer-string))))
973 (lambda () (apply #'string (mapcar #'1- v)))))))
974 (goto-char (point-min))
975 (let ((entries (auth-source-netrc-parse-entries check max))
976 alist)
977 (while (setq alist (pop entries))
978 (push (nreverse alist) result)))
980 (when (< 0 modified)
981 (when auth-source-gpg-encrypt-to
982 ;; (see bug#7487) making `epa-file-encrypt-to' local to
983 ;; this buffer lets epa-file skip the key selection query
984 ;; (see the `local-variable-p' check in
985 ;; `epa-file-write-region').
986 (unless (local-variable-p 'epa-file-encrypt-to (current-buffer))
987 (make-local-variable 'epa-file-encrypt-to))
988 (if (listp auth-source-gpg-encrypt-to)
989 (setq epa-file-encrypt-to auth-source-gpg-encrypt-to)))
991 ;; ask AFTER we've successfully opened the file
992 (when (y-or-n-p (format "Save file %s? (%d deletions)"
993 file modified))
994 (write-region (point-min) (point-max) file nil 'silent)
995 (auth-source-do-debug
996 "auth-source-netrc-parse: modified %d lines in %s"
997 modified file)))
999 (nreverse result))))))
1001 (defun auth-source-netrc-parse-next-interesting ()
1002 "Advance to the next interesting position in the current buffer."
1003 (skip-chars-forward "\t ")
1004 ;; If we're looking at a comment or are at the end of the line, move forward
1005 (while (or (eq (char-after) ?#)
1006 (and (eolp)
1007 (not (eobp))))
1008 (forward-line 1)
1009 (skip-chars-forward "\t ")))
1011 (defun auth-source-netrc-parse-one ()
1012 "Read one thing from the current buffer."
1013 (auth-source-netrc-parse-next-interesting)
1015 (when (or (looking-at "'\\([^']*\\)'")
1016 (looking-at "\"\\([^\"]*\\)\"")
1017 (looking-at "\\([^ \t\n]+\\)"))
1018 (forward-char (length (match-string 0)))
1019 (prog1
1020 (match-string-no-properties 1)
1021 (auth-source-netrc-parse-next-interesting))))
1023 ;; with thanks to org-mode
1024 (defsubst auth-source-current-line (&optional pos)
1025 (save-excursion
1026 (and pos (goto-char pos))
1027 ;; works also in narrowed buffer, because we start at 1, not point-min
1028 (+ (if (bolp) 1 0) (count-lines 1 (point)))))
1030 (defun auth-source-netrc-parse-entries(check max)
1031 "Parse up to MAX netrc entries, passed by CHECK, from the current buffer."
1032 (let ((adder (lambda(check alist all)
1033 (when (and
1034 alist
1035 (> max (length all))
1036 (funcall check alist))
1037 (push alist all))
1038 all))
1039 item item2 all alist default)
1040 (while (setq item (auth-source-netrc-parse-one))
1041 (setq default (equal item "default"))
1042 ;; We're starting a new machine. Save the old one.
1043 (when (and alist
1044 (or default
1045 (equal item "machine")))
1046 ;; (auth-source-do-trivia
1047 ;; "auth-source-netrc-parse-entries: got entry %S" alist)
1048 (setq all (funcall adder check alist all)
1049 alist nil))
1050 ;; In default entries, we don't have a next token.
1051 ;; We store them as ("machine" . t)
1052 (if default
1053 (push (cons "machine" t) alist)
1054 ;; Not a default entry. Grab the next item.
1055 (when (setq item2 (auth-source-netrc-parse-one))
1056 ;; Did we get a "machine" value?
1057 (if (equal item2 "machine")
1058 (error
1059 "%s: Unexpected `machine' token at line %d"
1060 "auth-source-netrc-parse-entries"
1061 (auth-source-current-line))
1062 (push (cons item item2) alist)))))
1064 ;; Clean up: if there's an entry left over, use it.
1065 (when alist
1066 (setq all (funcall adder check alist all))
1067 ;; (auth-source-do-trivia
1068 ;; "auth-source-netrc-parse-entries: got2 entry %S" alist)
1070 (nreverse all)))
1072 (defvar auth-source-passphrase-alist nil)
1074 (defun auth-source-token-passphrase-callback-function (_context _key-id file)
1075 (let* ((file (file-truename file))
1076 (entry (assoc file auth-source-passphrase-alist))
1077 passphrase)
1078 ;; return the saved passphrase, calling a function if needed
1079 (or (copy-sequence (if (functionp (cdr entry))
1080 (funcall (cdr entry))
1081 (cdr entry)))
1082 (progn
1083 (unless entry
1084 (setq entry (list file))
1085 (push entry auth-source-passphrase-alist))
1086 (setq passphrase
1087 (read-passwd
1088 (format "Passphrase for %s tokens: " file)
1090 (setcdr entry (let ((p (copy-sequence passphrase)))
1091 (lambda () p)))
1092 passphrase))))
1094 (defun auth-source-epa-extract-gpg-token (secret file)
1095 "Pass either the decoded SECRET or the gpg:BASE64DATA version.
1096 FILE is the file from which we obtained this token."
1097 (when (string-match "^gpg:\\(.+\\)" secret)
1098 (setq secret (base64-decode-string (match-string 1 secret))))
1099 (let ((context (epg-make-context 'OpenPGP)))
1100 (epg-context-set-passphrase-callback
1101 context
1102 (cons #'auth-source-token-passphrase-callback-function
1103 file))
1104 (epg-decrypt-string context secret)))
1106 (defvar pp-escape-newlines)
1108 (defun auth-source-epa-make-gpg-token (secret file)
1109 (let ((context (epg-make-context 'OpenPGP))
1110 (pp-escape-newlines nil)
1111 cipher)
1112 (setf (epg-context-armor context) t)
1113 (epg-context-set-passphrase-callback
1114 context
1115 (cons #'auth-source-token-passphrase-callback-function
1116 file))
1117 (setq cipher (epg-encrypt-string context secret nil))
1118 (with-temp-buffer
1119 (insert cipher)
1120 (base64-encode-region (point-min) (point-max) t)
1121 (concat "gpg:" (buffer-substring-no-properties
1122 (point-min)
1123 (point-max))))))
1125 (defun auth-source--symbol-keyword (symbol)
1126 (intern (format ":%s" symbol)))
1128 (defun auth-source-netrc-normalize (alist filename)
1129 (mapcar (lambda (entry)
1130 (let (ret item)
1131 (while (setq item (pop entry))
1132 (let ((k (car item))
1133 (v (cdr item)))
1135 ;; apply key aliases
1136 (setq k (cond ((member k '("machine")) "host")
1137 ((member k '("login" "account")) "user")
1138 ((member k '("protocol")) "port")
1139 ((member k '("password")) "secret")
1140 (t k)))
1142 ;; send back the secret in a function (lexical binding)
1143 (when (equal k "secret")
1144 (setq v (let ((lexv v)
1145 (token-decoder nil))
1146 (when (string-match "^gpg:" lexv)
1147 ;; it's a GPG token: create a token decoder
1148 ;; which unsets itself once
1149 (setq token-decoder
1150 (lambda (val)
1151 (prog1
1152 (auth-source-epa-extract-gpg-token
1154 filename)
1155 (setq token-decoder nil)))))
1156 (lambda ()
1157 (when token-decoder
1158 (setq lexv (funcall token-decoder lexv)))
1159 lexv))))
1160 (setq ret (plist-put ret
1161 (auth-source--symbol-keyword k)
1162 v))))
1163 ret))
1164 alist))
1166 (cl-defun auth-source-netrc-search (&rest spec
1167 &key backend require create
1168 type max host user port
1169 &allow-other-keys)
1170 "Given a property list SPEC, return search matches from the :backend.
1171 See `auth-source-search' for details on SPEC."
1172 ;; just in case, check that the type is correct (null or same as the backend)
1173 (cl-assert (or (null type) (eq type (oref backend type)))
1174 t "Invalid netrc search: %s %s")
1176 (let ((results (auth-source-netrc-normalize
1177 (auth-source-netrc-parse
1178 :max max
1179 :require require
1180 :file (oref backend source)
1181 :host (or host t)
1182 :user (or user t)
1183 :port (or port t))
1184 (oref backend source))))
1186 ;; if we need to create an entry AND none were found to match
1187 (when (and create
1188 (not results))
1190 ;; create based on the spec and record the value
1191 (setq results (or
1192 ;; if the user did not want to create the entry
1193 ;; in the file, it will be returned
1194 (apply (slot-value backend 'create-function) spec)
1195 ;; if not, we do the search again without :create
1196 ;; to get the updated data.
1198 ;; the result will be returned, even if the search fails
1199 (apply #'auth-source-netrc-search
1200 (plist-put spec :create nil)))))
1201 results))
1203 (defun auth-source-netrc-element-or-first (v)
1204 (if (listp v)
1205 (nth 0 v)
1208 ;; (auth-source-search :host "nonesuch" :type 'netrc :max 1 :create t)
1209 ;; (auth-source-search :host "nonesuch" :type 'netrc :max 1 :create t :create-extra-keys '((A "default A") (B)))
1211 (cl-defun auth-source-netrc-create (&rest spec
1212 &key backend host port create
1213 &allow-other-keys)
1214 (let* ((base-required '(host user port secret))
1215 ;; we know (because of an assertion in auth-source-search) that the
1216 ;; :create parameter is either t or a list (which includes nil)
1217 (create-extra (if (eq t create) nil create))
1218 (current-data (car (auth-source-search :max 1
1219 :host host
1220 :port port)))
1221 (required (append base-required create-extra))
1222 (file (oref backend source))
1223 (add "")
1224 ;; `valist' is an alist
1225 valist
1226 ;; `artificial' will be returned if no creation is needed
1227 artificial)
1229 ;; only for base required elements (defined as function parameters):
1230 ;; fill in the valist with whatever data we may have from the search
1231 ;; we complete the first value if it's a list and use the value otherwise
1232 (dolist (br base-required)
1233 (let ((val (plist-get spec (auth-source--symbol-keyword br))))
1234 (when val
1235 (let ((br-choice (cond
1236 ;; all-accepting choice (predicate is t)
1237 ((eq t val) nil)
1238 ;; just the value otherwise
1239 (t val))))
1240 (when br-choice
1241 (auth-source--aput valist br br-choice))))))
1243 ;; for extra required elements, see if the spec includes a value for them
1244 (dolist (er create-extra)
1245 (let ((k (auth-source--symbol-keyword er))
1246 (keys (cl-loop for i below (length spec) by 2
1247 collect (nth i spec))))
1248 (when (memq k keys)
1249 (auth-source--aput valist er (plist-get spec k)))))
1251 ;; for each required element
1252 (dolist (r required)
1253 (let* ((data (auth-source--aget valist r))
1254 ;; take the first element if the data is a list
1255 (data (or (auth-source-netrc-element-or-first data)
1256 (plist-get current-data
1257 (auth-source--symbol-keyword r))))
1258 ;; this is the default to be offered
1259 (given-default (auth-source--aget
1260 auth-source-creation-defaults r))
1261 ;; the default supplementals are simple:
1262 ;; for the user, try `given-default' and then (user-login-name);
1263 ;; otherwise take `given-default'
1264 (default (cond
1265 ((and (not given-default) (eq r 'user))
1266 (user-login-name))
1267 (t given-default)))
1268 (printable-defaults (list
1269 (cons 'user
1271 (auth-source-netrc-element-or-first
1272 (auth-source--aget valist 'user))
1273 (plist-get artificial :user)
1274 "[any user]"))
1275 (cons 'host
1277 (auth-source-netrc-element-or-first
1278 (auth-source--aget valist 'host))
1279 (plist-get artificial :host)
1280 "[any host]"))
1281 (cons 'port
1283 (auth-source-netrc-element-or-first
1284 (auth-source--aget valist 'port))
1285 (plist-get artificial :port)
1286 "[any port]"))))
1287 (prompt (or (auth-source--aget auth-source-creation-prompts r)
1288 (cl-case r
1289 (secret "%p password for %u@%h: ")
1290 (user "%p user name for %h: ")
1291 (host "%p host name for user %u: ")
1292 (port "%p port for %u@%h: "))
1293 (format "Enter %s (%%u@%%h:%%p): " r)))
1294 (prompt (auth-source-format-prompt
1295 prompt
1296 `((?u ,(auth-source--aget printable-defaults 'user))
1297 (?h ,(auth-source--aget printable-defaults 'host))
1298 (?p ,(auth-source--aget printable-defaults 'port))))))
1300 ;; Store the data, prompting for the password if needed.
1301 (setq data (or data
1302 (if (eq r 'secret)
1303 ;; Special case prompt for passwords.
1304 ;; 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)))
1305 ;; TODO: or maybe leave as (setq auth-source-netrc-use-gpg-tokens 'never)
1306 (let* ((ep (format "Use GPG password tokens in %s?" file))
1307 (gpg-encrypt
1308 (cond
1309 ((eq auth-source-netrc-use-gpg-tokens 'never)
1310 'never)
1311 ((listp auth-source-netrc-use-gpg-tokens)
1312 (let ((check (copy-sequence
1313 auth-source-netrc-use-gpg-tokens))
1314 item ret)
1315 (while check
1316 (setq item (pop check))
1317 (when (or (eq (car item) t)
1318 (string-match (car item) file))
1319 (setq ret (cdr item))
1320 (setq check nil)))
1321 ret))
1322 (t 'never)))
1323 (plain (or (eval default) (read-passwd prompt))))
1324 ;; ask if we don't know what to do (in which case
1325 ;; auth-source-netrc-use-gpg-tokens must be a list)
1326 (unless gpg-encrypt
1327 (setq gpg-encrypt (if (y-or-n-p ep) 'gpg 'never))
1328 ;; TODO: save the defcustom now? or ask?
1329 (setq auth-source-netrc-use-gpg-tokens
1330 (cons `(,file ,gpg-encrypt)
1331 auth-source-netrc-use-gpg-tokens)))
1332 (if (eq gpg-encrypt 'gpg)
1333 (auth-source-epa-make-gpg-token plain file)
1334 plain))
1335 (if (stringp default)
1336 (read-string (if (string-match ": *\\'" prompt)
1337 (concat (substring prompt 0 (match-beginning 0))
1338 " (default " default "): ")
1339 (concat prompt "(default " default ") "))
1340 nil nil default)
1341 (eval default)))))
1343 (when data
1344 (setq artificial (plist-put artificial
1345 (auth-source--symbol-keyword r)
1346 (if (eq r 'secret)
1347 (let ((data data))
1348 (lambda () data))
1349 data))))
1351 ;; When r is not an empty string...
1352 (when (and (stringp data)
1353 (< 0 (length data)))
1354 ;; this function is not strictly necessary but I think it
1355 ;; makes the code clearer -tzz
1356 (let ((printer (lambda ()
1357 ;; append the key (the symbol name of r)
1358 ;; and the value in r
1359 (format "%s%s %s"
1360 ;; prepend a space
1361 (if (zerop (length add)) "" " ")
1362 ;; remap auth-source tokens to netrc
1363 (cl-case r
1364 (user "login")
1365 (host "machine")
1366 (secret "password")
1367 (port "port") ; redundant but clearer
1368 (t (symbol-name r)))
1369 (if (string-match "[\"# ]" data)
1370 (format "%S" data)
1371 data)))))
1372 (setq add (concat add (funcall printer)))))))
1374 (plist-put
1375 artificial
1376 :save-function
1377 (let ((file file)
1378 (add add))
1379 (lambda () (auth-source-netrc-saver file add))))
1381 (list artificial)))
1383 (defun auth-source-netrc-saver (file add)
1384 "Save a line ADD in FILE, prompting along the way.
1385 Respects `auth-source-save-behavior'. Uses
1386 `auth-source-netrc-cache' to avoid prompting more than once."
1387 (let* ((key (format "%s %s" file (rfc2104-hash 'md5 64 16 file add)))
1388 (cached (assoc key auth-source-netrc-cache)))
1390 (if cached
1391 (auth-source-do-trivia
1392 "auth-source-netrc-saver: found previous run for key %s, returning"
1393 key)
1394 (with-temp-buffer
1395 (when (file-exists-p file)
1396 (insert-file-contents file))
1397 (when auth-source-gpg-encrypt-to
1398 ;; (see bug#7487) making `epa-file-encrypt-to' local to
1399 ;; this buffer lets epa-file skip the key selection query
1400 ;; (see the `local-variable-p' check in
1401 ;; `epa-file-write-region').
1402 (unless (local-variable-p 'epa-file-encrypt-to (current-buffer))
1403 (make-local-variable 'epa-file-encrypt-to))
1404 (if (listp auth-source-gpg-encrypt-to)
1405 (setq epa-file-encrypt-to auth-source-gpg-encrypt-to)))
1406 ;; we want the new data to be found first, so insert at beginning
1407 (goto-char (point-min))
1409 ;; Ask AFTER we've successfully opened the file.
1410 (let ((prompt (format "Save auth info to file %s? " file))
1411 (done (not (eq auth-source-save-behavior 'ask)))
1412 (bufname "*auth-source Help*")
1414 (while (not done)
1415 (setq k (auth-source-read-char-choice prompt '(?y ?n ?N ?e ??)))
1416 (cl-case k
1417 (?y (setq done t))
1418 (?? (save-excursion
1419 (with-output-to-temp-buffer bufname
1420 (princ
1421 (concat "(y)es, save\n"
1422 "(n)o but use the info\n"
1423 "(N)o and don't ask to save again\n"
1424 "(e)dit the line\n"
1425 "(?) for help as you can see.\n"))
1426 ;; Why? Doesn't with-output-to-temp-buffer already do
1427 ;; the exact same thing anyway? --Stef
1428 (set-buffer standard-output)
1429 (help-mode))))
1430 (?n (setq add ""
1431 done t))
1433 (setq add ""
1434 done t)
1435 (customize-save-variable 'auth-source-save-behavior nil))
1436 (?e (setq add (read-string "Line to add: " add)))
1437 (t nil)))
1439 (when (get-buffer-window bufname)
1440 (delete-window (get-buffer-window bufname)))
1442 ;; Make sure the info is not saved.
1443 (when (null auth-source-save-behavior)
1444 (setq add ""))
1446 (when (< 0 (length add))
1447 (progn
1448 (unless (bolp)
1449 (insert "\n"))
1450 (insert add "\n")
1451 (write-region (point-min) (point-max) file nil 'silent)
1452 ;; Make the .authinfo file non-world-readable.
1453 (set-file-modes file #o600)
1454 (auth-source-do-debug
1455 "auth-source-netrc-create: wrote 1 new line to %s"
1456 file)
1457 (message "Saved new authentication information to %s" file)
1458 nil))))
1459 (auth-source--aput auth-source-netrc-cache key "ran"))))
1461 ;;; Backend specific parsing: Secrets API backend
1463 (defun auth-source-secrets-listify-pattern (pattern)
1464 "Convert a pattern with lists to a list of string patterns.
1466 auth-source patterns can have values of the form :foo (\"bar\"
1467 \"qux\"), which means to match any secret with :foo equal to
1468 \"bar\" or :foo equal to \"qux\". The secrets backend supports
1469 only string values for patterns, so this routine returns a list
1470 of patterns that is equivalent to the single original pattern
1471 when interpreted such that if a secret matches any pattern in the
1472 list, it matches the original pattern."
1473 (if (null pattern)
1474 '(nil)
1475 (let* ((key (pop pattern))
1476 (value (pop pattern))
1477 (tails (auth-source-secrets-listify-pattern pattern))
1478 (heads (if (stringp value)
1479 (list (list key value))
1480 (mapcar (lambda (v) (list key v)) value))))
1481 (cl-loop for h in heads
1482 nconc (cl-loop for tl in tails collect (append h tl))))))
1484 (cl-defun auth-source-secrets-search (&rest spec
1485 &key backend create delete label max
1486 &allow-other-keys)
1487 "Search the Secrets API; spec is like `auth-source'.
1489 The :label key specifies the item's label. It is the only key
1490 that can specify a substring. Any :label value besides a string
1491 will allow any label.
1493 All other search keys must match exactly. If you need substring
1494 matching, do a wider search and narrow it down yourself.
1496 You'll get back all the properties of the token as a plist.
1498 Here's an example that looks for the first item in the `Login'
1499 Secrets collection:
1501 (let ((auth-sources \\='(\"secrets:Login\")))
1502 (auth-source-search :max 1))
1504 Here's another that looks for the first item in the `Login'
1505 Secrets collection whose label contains `gnus':
1507 (let ((auth-sources \\='(\"secrets:Login\")))
1508 (auth-source-search :max 1 :label \"gnus\"))
1510 And this one looks for the first item in the `Login' Secrets
1511 collection that's a Google Chrome entry for the git.gnus.org site
1512 authentication tokens:
1514 (let ((auth-sources \\='(\"secrets:Login\")))
1515 (auth-source-search :max 1 :signon_realm \"https://git.gnus.org/Git\"))
1518 ;; TODO
1519 ;; (secrets-delete-item coll elt)
1520 (cl-assert (not delete) nil
1521 "The Secrets API auth-source backend doesn't support deletion yet")
1523 (let* ((coll (oref backend source))
1524 (max (or max 5000)) ; sanity check: default to stop at 5K
1525 (ignored-keys '(:create :delete :max :backend :label :require :type))
1526 (search-keys (cl-loop for i below (length spec) by 2
1527 unless (memq (nth i spec) ignored-keys)
1528 collect (nth i spec)))
1529 ;; build a search spec without the ignored keys
1530 ;; if a search key is nil or t (match anything), we skip it
1531 (search-specs (auth-source-secrets-listify-pattern
1532 (apply #'append (mapcar
1533 (lambda (k)
1534 (if (or (null (plist-get spec k))
1535 (eq t (plist-get spec k)))
1537 (list k (plist-get spec k))))
1538 search-keys))))
1539 ;; needed keys (always including host, login, port, and secret)
1540 (returned-keys (delete-dups (append
1541 '(:host :login :port :secret)
1542 search-keys)))
1543 (items
1544 (cl-loop
1545 for search-spec in search-specs
1546 nconc
1547 (cl-loop for item in (apply #'secrets-search-items coll search-spec)
1548 unless (and (stringp label)
1549 (not (string-match label item)))
1550 collect item)))
1551 ;; TODO: respect max in `secrets-search-items', not after the fact
1552 (items (butlast items (- (length items) max)))
1553 ;; convert the item name to a full plist
1554 (items (mapcar (lambda (item)
1555 (append
1556 ;; make an entry for the secret (password) element
1557 (list
1558 :secret
1559 (let ((v (secrets-get-secret coll item)))
1560 (lambda () v)))
1561 ;; rewrite the entry from ((k1 v1) (k2 v2)) to plist
1562 (apply #'append
1563 (mapcar (lambda (entry)
1564 (list (car entry) (cdr entry)))
1565 (secrets-get-attributes coll item)))))
1566 items))
1567 ;; ensure each item has each key in `returned-keys'
1568 (items (mapcar (lambda (plist)
1569 (append
1570 (apply #'append
1571 (mapcar (lambda (req)
1572 (if (plist-get plist req)
1574 (list req nil)))
1575 returned-keys))
1576 plist))
1577 items)))
1578 (cond
1579 ;; if we need to create an entry AND none were found to match
1580 ((and create
1581 (not items))
1583 ;; create based on the spec and record the value
1584 (setq items (or
1585 ;; if the user did not want to create the entry
1586 ;; in the file, it will be returned
1587 (apply (slot-value backend 'create-function) spec)
1588 ;; if not, we do the search again without :create
1589 ;; to get the updated data.
1591 ;; the result will be returned, even if the search fails
1592 (apply #'auth-source-secrets-search
1593 (plist-put spec :create nil))))))
1594 items))
1596 (cl-defun auth-source-secrets-create (&rest spec
1597 &key backend host port create
1598 &allow-other-keys)
1599 (let* ((base-required '(host user port secret label))
1600 ;; we know (because of an assertion in auth-source-search) that the
1601 ;; :create parameter is either t or a list (which includes nil)
1602 (create-extra (if (eq t create) nil create))
1603 (current-data (car (auth-source-search :max 1
1604 :host host
1605 :port port)))
1606 (required (append base-required create-extra))
1607 (collection (oref backend source))
1608 ;; `args' are the arguments for `secrets-create-item'.
1609 args
1610 ;; `valist' is an alist
1611 valist
1612 ;; `artificial' will be returned if no creation is needed
1613 artificial)
1615 ;; only for base required elements (defined as function parameters):
1616 ;; fill in the valist with whatever data we may have from the search
1617 ;; we complete the first value if it's a list and use the value otherwise
1618 (dolist (br base-required)
1619 (let ((val (plist-get spec (auth-source--symbol-keyword br))))
1620 (when val
1621 (let ((br-choice (cond
1622 ;; all-accepting choice (predicate is t)
1623 ((eq t val) nil)
1624 ;; just the value otherwise
1625 (t val))))
1626 (when br-choice
1627 (auth-source--aput valist br br-choice))))))
1629 ;; for extra required elements, see if the spec includes a value for them
1630 (dolist (er create-extra)
1631 (let ((k (auth-source--symbol-keyword er))
1632 (keys (cl-loop for i below (length spec) by 2
1633 collect (nth i spec))))
1634 (when (memq k keys)
1635 (auth-source--aput valist er (plist-get spec k)))))
1637 ;; for each required element
1638 (dolist (r required)
1639 (let* ((data (auth-source--aget valist r))
1640 ;; take the first element if the data is a list
1641 (data (or (auth-source-netrc-element-or-first data)
1642 (plist-get current-data
1643 (auth-source--symbol-keyword r))))
1644 ;; this is the default to be offered
1645 (given-default (auth-source--aget
1646 auth-source-creation-defaults r))
1647 ;; the default supplementals are simple:
1648 ;; for the user, try `given-default' and then (user-login-name);
1649 ;; for the label, try `given-default' and then user@host;
1650 ;; otherwise take `given-default'
1651 (default (cond
1652 ((and (not given-default) (eq r 'user))
1653 (user-login-name))
1654 ((and (not given-default) (eq r 'label))
1655 (format "%s@%s"
1656 (or (auth-source-netrc-element-or-first
1657 (auth-source--aget valist 'user))
1658 (plist-get artificial :user))
1659 (or (auth-source-netrc-element-or-first
1660 (auth-source--aget valist 'host))
1661 (plist-get artificial :host))))
1662 (t given-default)))
1663 (printable-defaults (list
1664 (cons 'user
1666 (auth-source-netrc-element-or-first
1667 (auth-source--aget valist 'user))
1668 (plist-get artificial :user)
1669 "[any user]"))
1670 (cons 'host
1672 (auth-source-netrc-element-or-first
1673 (auth-source--aget valist 'host))
1674 (plist-get artificial :host)
1675 "[any host]"))
1676 (cons 'port
1678 (auth-source-netrc-element-or-first
1679 (auth-source--aget valist 'port))
1680 (plist-get artificial :port)
1681 "[any port]"))
1682 (cons 'label
1684 (auth-source-netrc-element-or-first
1685 (auth-source--aget valist 'label))
1686 (plist-get artificial :label)
1687 "[any label]"))))
1688 (prompt (or (auth-source--aget auth-source-creation-prompts r)
1689 (cl-case r
1690 (secret "%p password for %u@%h: ")
1691 (user "%p user name for %h: ")
1692 (host "%p host name for user %u: ")
1693 (port "%p port for %u@%h: ")
1694 (label "Enter label for %u@%h: "))
1695 (format "Enter %s (%%u@%%h:%%p): " r)))
1696 (prompt (auth-source-format-prompt
1697 prompt
1698 `((?u ,(auth-source--aget printable-defaults 'user))
1699 (?h ,(auth-source--aget printable-defaults 'host))
1700 (?p ,(auth-source--aget printable-defaults 'port))))))
1702 ;; Store the data, prompting for the password if needed.
1703 (setq data (or data
1704 (if (eq r 'secret)
1705 (or (eval default) (read-passwd prompt))
1706 (if (stringp default)
1707 (read-string (if (string-match ": *\\'" prompt)
1708 (concat (substring prompt 0 (match-beginning 0))
1709 " (default " default "): ")
1710 (concat prompt "(default " default ") "))
1711 nil nil default)
1712 (eval default)))))
1714 (when data
1715 (setq artificial (plist-put artificial
1716 (auth-source--symbol-keyword r)
1717 (if (eq r 'secret)
1718 (let ((data data))
1719 (lambda () data))
1720 data))))
1722 ;; When r is not an empty string...
1723 (when (and (stringp data)
1724 (< 0 (length data))
1725 (not (member r '(secret label))))
1726 ;; append the key (the symbol name of r)
1727 ;; and the value in r
1728 (setq args (append args (list (auth-source--symbol-keyword r) data))))))
1730 (plist-put
1731 artificial
1732 :save-function
1733 (let* ((collection collection)
1734 (item (plist-get artificial :label))
1735 (secret (plist-get artificial :secret))
1736 (secret (if (functionp secret) (funcall secret) secret)))
1737 (lambda ()
1738 (auth-source-secrets-saver collection item secret args))))
1740 (list artificial)))
1742 (defun auth-source-secrets-saver (collection item secret args)
1743 "Wrapper around `secrets-create-item', prompting along the way.
1744 Respects `auth-source-save-behavior'."
1745 (let ((prompt (format "Save auth info to secrets collection %s? " collection))
1746 (done (not (eq auth-source-save-behavior 'ask)))
1747 (doit (eq auth-source-save-behavior t))
1748 (bufname "*auth-source Help*")
1750 (while (not done)
1751 (setq k (auth-source-read-char-choice prompt '(?y ?n ?N ??)))
1752 (cl-case k
1753 (?y (setq done t doit t))
1754 (?? (save-excursion
1755 (with-output-to-temp-buffer bufname
1756 (princ
1757 (concat "(y)es, save\n"
1758 "(n)o but use the info\n"
1759 "(N)o and don't ask to save again\n"
1760 "(?) for help as you can see.\n"))
1761 ;; Why? Doesn't with-output-to-temp-buffer already do
1762 ;; the exact same thing anyway? --Stef
1763 (set-buffer standard-output)
1764 (help-mode))))
1765 (?n (setq done t doit nil))
1766 (?N (setq done t doit nil)
1767 (customize-save-variable 'auth-source-save-behavior nil))
1768 (t nil)))
1770 (when doit
1771 (progn
1772 (auth-source-do-debug
1773 "secrets-create-item: wrote 1 new item to %s" collection)
1774 (message "Saved new authentication information to %s" collection)
1775 (apply 'secrets-create-item collection item secret args)))))
1777 ;;; Backend specific parsing: Mac OS Keychain (using /usr/bin/security) backend
1779 (cl-defun auth-source-macos-keychain-search (&rest spec
1780 &key backend create delete type max
1781 &allow-other-keys)
1782 "Search the macOS Keychain; spec is like `auth-source'.
1784 All search keys must match exactly. If you need substring
1785 matching, do a wider search and narrow it down yourself.
1787 You'll get back all the properties of the token as a plist.
1789 The :type key is either `macos-keychain-internet' or
1790 `macos-keychain-generic'.
1792 For the internet keychain type, the :label key searches the
1793 item's labels (\"-l LABEL\" passed to \"/usr/bin/security\").
1794 Similarly, :host maps to \"-s HOST\", :user maps to \"-a USER\",
1795 and :port maps to \"-P PORT\" or \"-r PROT\"
1796 \(note PROT has to be a 4-character string).
1798 For the generic keychain type, the :label key searches the item's
1799 labels (\"-l LABEL\" passed to \"/usr/bin/security\").
1800 Similarly, :host maps to \"-c HOST\" (the \"creator\" keychain
1801 field), :user maps to \"-a USER\", and :port maps to \"-s PORT\".
1803 Here's an example that looks for the first item in the default
1804 generic macOS Keychain:
1806 (let ((auth-sources \\='(macos-keychain-generic)))
1807 (auth-source-search :max 1)
1809 Here's another that looks for the first item in the internet
1810 macOS Keychain collection whose label is `gnus':
1812 (let ((auth-sources \\='(macos-keychain-internet)))
1813 (auth-source-search :max 1 :label \"gnus\")
1815 And this one looks for the first item in the internet keychain
1816 entries for git.gnus.org:
1818 (let ((auth-sources \\='(macos-keychain-internet\")))
1819 (auth-source-search :max 1 :host \"git.gnus.org\"))
1821 ;; TODO
1822 (cl-assert (not create) nil
1823 "The macOS Keychain auth-source backend doesn't support creation yet")
1824 ;; TODO
1825 ;; (macos-keychain-delete-item coll elt)
1826 (cl-assert (not delete) nil
1827 "The macOS Keychain auth-source backend doesn't support deletion yet")
1829 (let* ((coll (oref backend source))
1830 (max (or max 5000)) ; sanity check: default to stop at 5K
1831 ;; Filter out ignored keys from the spec
1832 (ignored-keys '(:create :delete :max :backend :label :host :port))
1833 ;; Build a search spec without the ignored keys
1834 ;; FIXME make this loop a function? it's used in at least 3 places
1835 (search-keys (cl-loop for i below (length spec) by 2
1836 unless (memq (nth i spec) ignored-keys)
1837 collect (nth i spec)))
1838 ;; If a search key value is nil or t (match anything), we skip it
1839 (search-spec (apply #'append (mapcar
1840 (lambda (k)
1841 (if (or (null (plist-get spec k))
1842 (eq t (plist-get spec k)))
1844 (list k (plist-get spec k))))
1845 search-keys)))
1846 ;; needed keys (always including host, login, port, and secret)
1847 (returned-keys (delete-dups (append
1848 '(:host :login :port :secret)
1849 search-keys)))
1850 ;; Extract host and port from spec
1851 (hosts (plist-get spec :host))
1852 (hosts (if (and hosts (listp hosts)) hosts `(,hosts)))
1853 (ports (plist-get spec :port))
1854 (ports (if (and ports (listp ports)) ports `(,ports)))
1855 ;; Loop through all combinations of host/port and pass each of these to
1856 ;; auth-source-macos-keychain-search-items
1857 (items (catch 'match
1858 (dolist (host hosts)
1859 (dolist (port ports)
1860 (let* ((port (if port (format "%S" port)))
1861 (items (apply #'auth-source-macos-keychain-search-items
1862 coll
1863 type
1865 host port
1866 search-spec)))
1867 (when items
1868 (throw 'match items)))))))
1870 ;; ensure each item has each key in `returned-keys'
1871 (items (mapcar (lambda (plist)
1872 (append
1873 (apply #'append
1874 (mapcar (lambda (req)
1875 (if (plist-get plist req)
1877 (list req nil)))
1878 returned-keys))
1879 plist))
1880 items)))
1881 items))
1884 (defun auth-source--decode-octal-string (string)
1885 "Convert octal string to utf-8 string. E.g: 'a\134b' to 'a\b'"
1886 (let ((list (string-to-list string))
1887 (size (length string)))
1888 (decode-coding-string
1889 (apply #'unibyte-string
1890 (cl-loop for i = 0 then (+ i (if (eq (nth i list) ?\\) 4 1))
1891 for var = (nth i list)
1892 while (< i size)
1893 if (eq var ?\\)
1894 collect (string-to-number
1895 (concat (cl-subseq list (+ i 1) (+ i 4))) 8)
1896 else
1897 collect var))
1898 'utf-8)))
1900 (cl-defun auth-source-macos-keychain-search-items (coll _type _max host port
1901 &key label type user
1902 &allow-other-keys)
1903 (let* ((keychain-generic (eq type 'macos-keychain-generic))
1904 (args `(,(if keychain-generic
1905 "find-generic-password"
1906 "find-internet-password")
1907 "-g"))
1908 (ret (list :type type)))
1909 (when label
1910 (setq args (append args (list "-l" label))))
1911 (when host
1912 (setq args (append args (list (if keychain-generic "-c" "-s") host))))
1913 (when user
1914 (setq args (append args (list "-a" user))))
1916 (when port
1917 (if keychain-generic
1918 (setq args (append args (list "-s" port)))
1919 (setq args (append args (list
1920 (if (string-match "[0-9]+" port) "-P" "-r")
1921 port)))))
1923 (unless (equal coll "default")
1924 (setq args (append args (list coll))))
1926 (with-temp-buffer
1927 (apply #'call-process "/usr/bin/security" nil t nil args)
1928 (goto-char (point-min))
1929 (while (not (eobp))
1930 (cond
1931 ((looking-at "^password: \\(?:0x[0-9A-F]+\\)? *\"\\(.+\\)\"")
1932 (setq ret (auth-source-macos-keychain-result-append
1934 keychain-generic
1935 "secret"
1936 (let ((v (auth-source--decode-octal-string
1937 (match-string 1))))
1938 (lambda () v)))))
1939 ;; TODO: check if this is really the label
1940 ;; match 0x00000007 <blob>="AppleID"
1941 ((looking-at
1942 "^[ ]+0x00000007 <blob>=\\(?:0x[0-9A-F]+\\)? *\"\\(.+\\)\"")
1943 (setq ret (auth-source-macos-keychain-result-append
1945 keychain-generic
1946 "label"
1947 (auth-source--decode-octal-string (match-string 1)))))
1948 ;; match "crtr"<uint32>="aapl"
1949 ;; match "svce"<blob>="AppleID"
1950 ((looking-at
1951 "^[ ]+\"\\([a-z]+\\)\"[^=]+=\\(?:0x[0-9A-F]+\\)? *\"\\(.+\\)\"")
1952 (setq ret (auth-source-macos-keychain-result-append
1954 keychain-generic
1955 (auth-source--decode-octal-string (match-string 1))
1956 (auth-source--decode-octal-string (match-string 2))))))
1957 (forward-line)))
1958 ;; return `ret' iff it has the :secret key
1959 (and (plist-get ret :secret) (list ret))))
1961 (defun auth-source-macos-keychain-result-append (result generic k v)
1962 (push v result)
1963 (push (auth-source--symbol-keyword
1964 (cond
1965 ((equal k "acct") "user")
1966 ;; for generic keychains, creator is host, service is port
1967 ((and generic (equal k "crtr")) "host")
1968 ((and generic (equal k "svce")) "port")
1969 ;; for internet keychains, protocol is port, server is host
1970 ((and (not generic) (equal k "ptcl")) "port")
1971 ((and (not generic) (equal k "srvr")) "host")
1972 (t k)))
1973 result))
1975 (defun auth-source-macos-keychain-create (&rest spec)
1976 ;; TODO
1977 (debug spec))
1979 ;;; Backend specific parsing: PLSTORE backend
1981 (cl-defun auth-source-plstore-search (&rest spec
1982 &key backend create delete max
1983 &allow-other-keys)
1984 "Search the PLSTORE; spec is like `auth-source'."
1985 (let* ((store (oref backend data))
1986 (max (or max 5000)) ; sanity check: default to stop at 5K
1987 (ignored-keys '(:create :delete :max :backend :label :require :type))
1988 (search-keys (cl-loop for i below (length spec) by 2
1989 unless (memq (nth i spec) ignored-keys)
1990 collect (nth i spec)))
1991 ;; build a search spec without the ignored keys
1992 ;; if a search key is nil or t (match anything), we skip it
1993 (search-spec (apply #'append (mapcar
1994 (lambda (k)
1995 (let ((v (plist-get spec k)))
1996 (if (or (null v)
1997 (eq t v))
1999 (if (stringp v)
2000 (setq v (list v)))
2001 (list k v))))
2002 search-keys)))
2003 ;; needed keys (always including host, login, port, and secret)
2004 (returned-keys (delete-dups (append
2005 '(:host :login :port :secret)
2006 search-keys)))
2007 (items (plstore-find store search-spec))
2008 (item-names (mapcar #'car items))
2009 (items (butlast items (- (length items) max)))
2010 ;; convert the item to a full plist
2011 (items (mapcar (lambda (item)
2012 (let* ((plist (copy-tree (cdr item)))
2013 (secret (plist-member plist :secret)))
2014 (if secret
2015 (setcar
2016 (cdr secret)
2017 (let ((v (car (cdr secret))))
2018 (lambda () v))))
2019 plist))
2020 items))
2021 ;; ensure each item has each key in `returned-keys'
2022 (items (mapcar (lambda (plist)
2023 (append
2024 (apply #'append
2025 (mapcar (lambda (req)
2026 (if (plist-get plist req)
2028 (list req nil)))
2029 returned-keys))
2030 plist))
2031 items)))
2032 (cond
2033 ;; if we need to create an entry AND none were found to match
2034 ((and create
2035 (not items))
2037 ;; create based on the spec and record the value
2038 (setq items (or
2039 ;; if the user did not want to create the entry
2040 ;; in the file, it will be returned
2041 (apply (slot-value backend 'create-function) spec)
2042 ;; if not, we do the search again without :create
2043 ;; to get the updated data.
2045 ;; the result will be returned, even if the search fails
2046 (apply #'auth-source-plstore-search
2047 (plist-put spec :create nil)))))
2048 ((and delete
2049 item-names)
2050 (dolist (item-name item-names)
2051 (plstore-delete store item-name))
2052 (plstore-save store)))
2053 items))
2055 (cl-defun auth-source-plstore-create (&rest spec
2056 &key backend host port create
2057 &allow-other-keys)
2058 (let* ((base-required '(host user port secret))
2059 (base-secret '(secret))
2060 ;; we know (because of an assertion in auth-source-search) that the
2061 ;; :create parameter is either t or a list (which includes nil)
2062 (create-extra (if (eq t create) nil create))
2063 (current-data (car (auth-source-search :max 1
2064 :host host
2065 :port port)))
2066 (required (append base-required create-extra))
2067 ;; `valist' is an alist
2068 valist
2069 ;; `artificial' will be returned if no creation is needed
2070 artificial
2071 secret-artificial)
2073 ;; only for base required elements (defined as function parameters):
2074 ;; fill in the valist with whatever data we may have from the search
2075 ;; we complete the first value if it's a list and use the value otherwise
2076 (dolist (br base-required)
2077 (let ((val (plist-get spec (auth-source--symbol-keyword br))))
2078 (when val
2079 (let ((br-choice (cond
2080 ;; all-accepting choice (predicate is t)
2081 ((eq t val) nil)
2082 ;; just the value otherwise
2083 (t val))))
2084 (when br-choice
2085 (auth-source--aput valist br br-choice))))))
2087 ;; for extra required elements, see if the spec includes a value for them
2088 (dolist (er create-extra)
2089 (let ((k (auth-source--symbol-keyword er))
2090 (keys (cl-loop for i below (length spec) by 2
2091 collect (nth i spec))))
2092 (when (memq k keys)
2093 (auth-source--aput valist er (plist-get spec k)))))
2095 ;; for each required element
2096 (dolist (r required)
2097 (let* ((data (auth-source--aget valist r))
2098 ;; take the first element if the data is a list
2099 (data (or (auth-source-netrc-element-or-first data)
2100 (plist-get current-data
2101 (auth-source--symbol-keyword r))))
2102 ;; this is the default to be offered
2103 (given-default (auth-source--aget
2104 auth-source-creation-defaults r))
2105 ;; the default supplementals are simple:
2106 ;; for the user, try `given-default' and then (user-login-name);
2107 ;; otherwise take `given-default'
2108 (default (cond
2109 ((and (not given-default) (eq r 'user))
2110 (user-login-name))
2111 (t given-default)))
2112 (printable-defaults (list
2113 (cons 'user
2115 (auth-source-netrc-element-or-first
2116 (auth-source--aget valist 'user))
2117 (plist-get artificial :user)
2118 "[any user]"))
2119 (cons 'host
2121 (auth-source-netrc-element-or-first
2122 (auth-source--aget valist 'host))
2123 (plist-get artificial :host)
2124 "[any host]"))
2125 (cons 'port
2127 (auth-source-netrc-element-or-first
2128 (auth-source--aget valist 'port))
2129 (plist-get artificial :port)
2130 "[any port]"))))
2131 (prompt (or (auth-source--aget auth-source-creation-prompts r)
2132 (cl-case r
2133 (secret "%p password for %u@%h: ")
2134 (user "%p user name for %h: ")
2135 (host "%p host name for user %u: ")
2136 (port "%p port for %u@%h: "))
2137 (format "Enter %s (%%u@%%h:%%p): " r)))
2138 (prompt (auth-source-format-prompt
2139 prompt
2140 `((?u ,(auth-source--aget printable-defaults 'user))
2141 (?h ,(auth-source--aget printable-defaults 'host))
2142 (?p ,(auth-source--aget printable-defaults 'port))))))
2144 ;; Store the data, prompting for the password if needed.
2145 (setq data (or data
2146 (if (eq r 'secret)
2147 (or (eval default) (read-passwd prompt))
2148 (if (stringp default)
2149 (read-string
2150 (if (string-match ": *\\'" prompt)
2151 (concat (substring prompt 0 (match-beginning 0))
2152 " (default " default "): ")
2153 (concat prompt "(default " default ") "))
2154 nil nil default)
2155 (eval default)))))
2157 (when data
2158 (if (member r base-secret)
2159 (setq secret-artificial
2160 (plist-put secret-artificial
2161 (auth-source--symbol-keyword r)
2162 data))
2163 (setq artificial (plist-put artificial
2164 (auth-source--symbol-keyword r)
2165 data))))))
2166 (plstore-put (oref backend data)
2167 (sha1 (format "%s@%s:%s"
2168 (plist-get artificial :user)
2169 (plist-get artificial :host)
2170 (plist-get artificial :port)))
2171 artificial secret-artificial)
2172 (if (y-or-n-p (format "Save auth info to file %s? "
2173 (plstore-get-file (oref backend data))))
2174 (plstore-save (oref backend data)))))
2176 ;;; Backend specific parsing: JSON backend
2177 ;;; (auth-source-search :max 1 :machine "imap.gmail.com")
2178 ;;; (auth-source-search :max 1 :host '("my-gmail" "imap.gmail.com") :port '(993 "imaps" "imap" "993" "143") :user nil :require '(:user :secret))
2180 (defun auth-source-json-check (host user port require item)
2181 (and item
2182 (auth-source-search-collection
2183 (or host t)
2185 (plist-get item :machine)
2186 (plist-get item :host)
2188 (auth-source-search-collection
2189 (or user t)
2191 (plist-get item :login)
2192 (plist-get item :account)
2193 (plist-get item :user)
2195 (auth-source-search-collection
2196 (or port t)
2198 (plist-get item :port)
2199 (plist-get item :protocol)
2202 ;; the required list of keys is nil, or
2203 (null require)
2204 ;; every element of require is in
2205 (cl-loop for req in require
2206 always (plist-get item req)))))
2208 (cl-defun auth-source-json-search (&rest spec
2209 &key backend require
2210 type max host user port
2211 &allow-other-keys)
2212 "Given a property list SPEC, return search matches from the :backend.
2213 See `auth-source-search' for details on SPEC."
2214 ;; just in case, check that the type is correct (null or same as the backend)
2215 (cl-assert (or (null type) (eq type (oref backend type)))
2216 t "Invalid JSON search: %s %s")
2218 ;; Hide the secrets early to avoid accidental exposure.
2219 (let* ((jdata
2220 (mapcar (lambda (entry)
2221 (let (ret)
2222 (while entry
2223 (let* ((item (pop entry))
2224 (k (auth-source--symbol-keyword (car item)))
2225 (v (cdr item)))
2226 (setq k (cond ((memq k '(:machine)) :host)
2227 ((memq k '(:login :account)) :user)
2228 ((memq k '(:protocol)) :port)
2229 ((memq k '(:password)) :secret)
2230 (t k)))
2231 ;; send back the secret in a function (lexical binding)
2232 (when (eq k :secret)
2233 (setq v (let ((lexv v))
2234 (lambda () lexv))))
2235 (setq ret (plist-put ret k v))))
2236 ret))
2237 (json-read-file (oref backend source))))
2238 (max (or max 5000)) ; sanity check: default to stop at 5K
2239 all)
2240 (dolist (item jdata)
2241 (when (and item
2242 (> max (length all))
2243 (auth-source-json-check host user port require item))
2244 (push item all)))
2245 (nreverse all)))
2247 ;;; older API
2249 ;; (auth-source-user-or-password '("login" "password") "imap.myhost.com" t "tzz")
2251 ;; deprecate the old interface
2252 (make-obsolete 'auth-source-user-or-password
2253 'auth-source-search "Emacs 24.1")
2254 (make-obsolete 'auth-source-forget-user-or-password
2255 'auth-source-forget "Emacs 24.1")
2257 (defun auth-source-user-or-password
2258 (mode host port &optional username create-missing delete-existing)
2259 "Find MODE (string or list of strings) matching HOST and PORT.
2261 DEPRECATED in favor of `auth-source-search'!
2263 USERNAME is optional and will be used as \"login\" in a search
2264 across the Secret Service API (see secrets.el) if the resulting
2265 items don't have a username. This means that if you search for
2266 username \"joe\" and it matches an item but the item doesn't have
2267 a :user attribute, the username \"joe\" will be returned.
2269 A non nil DELETE-EXISTING means deleting any matching password
2270 entry in the respective sources. This is useful only when
2271 CREATE-MISSING is non nil as well; the intended use case is to
2272 remove wrong password entries.
2274 If no matching entry is found, and CREATE-MISSING is non nil,
2275 the password will be retrieved interactively, and it will be
2276 stored in the password database which matches best (see
2277 `auth-sources').
2279 MODE can be \"login\" or \"password\"."
2280 (auth-source-do-debug
2281 "auth-source-user-or-password: DEPRECATED get %s for %s (%s) + user=%s"
2282 mode host port username)
2284 (let* ((listy (listp mode))
2285 (mode (if listy mode (list mode)))
2286 ;; (cname (if username
2287 ;; (format "%s %s:%s %s" mode host port username)
2288 ;; (format "%s %s:%s" mode host port)))
2289 (search (list :host host :port port))
2290 (search (if username (append search (list :user username)) search))
2291 (search (if create-missing
2292 (append search (list :create t))
2293 search))
2294 (search (if delete-existing
2295 (append search (list :delete t))
2296 search))
2297 ;; (found (if (not delete-existing)
2298 ;; (gethash cname auth-source-cache)
2299 ;; (remhash cname auth-source-cache)
2300 ;; nil)))
2301 (found nil))
2302 (if found
2303 (progn
2304 (auth-source-do-debug
2305 "auth-source-user-or-password: DEPRECATED cached %s=%s for %s (%s) + %s"
2306 mode
2307 ;; don't show the password
2308 (if (and (member "password" mode) t)
2309 "SECRET"
2310 found)
2311 host port username)
2312 found) ; return the found data
2313 ;; else, if not found, search with a max of 1
2314 (let ((choice (nth 0 (apply #'auth-source-search
2315 (append '(:max 1) search)))))
2316 (when choice
2317 (dolist (m mode)
2318 (cond
2319 ((equal "password" m)
2320 (push (if (plist-get choice :secret)
2321 (funcall (plist-get choice :secret))
2322 nil) found))
2323 ((equal "login" m)
2324 (push (plist-get choice :user) found)))))
2325 (setq found (nreverse found))
2326 (setq found (if listy found (car-safe found)))))
2328 found))
2330 (defun auth-source-user-and-password (host &optional user)
2331 (let* ((auth-info (car
2332 (if user
2333 (auth-source-search
2334 :host host
2335 :user user
2336 :max 1
2337 :require '(:user :secret)
2338 :create nil)
2339 (auth-source-search
2340 :host host
2341 :max 1
2342 :require '(:user :secret)
2343 :create nil))))
2344 (user (plist-get auth-info :user))
2345 (password (plist-get auth-info :secret)))
2346 (when (functionp password)
2347 (setq password (funcall password)))
2348 (list user password auth-info)))
2350 (provide 'auth-source)
2352 ;;; auth-source.el ends here