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>
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/>.
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.
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
42 (require 'password-cache
)
44 (eval-when-compile (require 'cl-lib
))
47 (autoload 'secrets-create-item
"secrets")
48 (autoload 'secrets-delete-item
"secrets")
49 (autoload 'secrets-get-alias
"secrets")
50 (autoload 'secrets-get-attributes
"secrets")
51 (autoload 'secrets-get-secret
"secrets")
52 (autoload 'secrets-list-collections
"secrets")
53 (autoload 'secrets-search-items
"secrets")
55 (autoload 'rfc2104-hash
"rfc2104")
57 (autoload 'plstore-open
"plstore")
58 (autoload 'plstore-find
"plstore")
59 (autoload 'plstore-put
"plstore")
60 (autoload 'plstore-delete
"plstore")
61 (autoload 'plstore-save
"plstore")
62 (autoload 'plstore-get-file
"plstore")
64 (eval-when-compile (require 'epg
)) ;; setf-method for `epg-context-armor'
65 (autoload 'epg-make-context
"epg")
66 (autoload 'epg-context-set-passphrase-callback
"epg")
67 (autoload 'epg-decrypt-string
"epg")
68 (autoload 'epg-encrypt-string
"epg")
70 (autoload 'help-mode
"help-mode" nil t
)
72 (defvar secrets-enabled
)
74 (defgroup auth-source nil
75 "Authentication sources."
76 :version
"23.1" ;; No Gnus
80 (defcustom auth-source-cache-expiry
7200
81 "How many seconds passwords are cached, or nil to disable
82 expiring. Overrides `password-cache-expiry' through a
86 :type
'(choice (const :tag
"Never" nil
)
87 (const :tag
"All Day" 86400)
88 (const :tag
"2 Hours" 7200)
89 (const :tag
"30 Minutes" 1800)
90 (integer :tag
"Seconds")))
92 ;; The slots below correspond with the `auth-source-search' spec,
93 ;; so a backend with :host set, for instance, would match only
94 ;; searches for that host. Normally they are nil.
95 (defclass auth-source-backend
()
100 :documentation
"The backend type.")
101 (source :initarg
:source
104 :documentation
"The backend source.")
109 :documentation
"The backend host.")
114 :documentation
"The backend user.")
119 :documentation
"The backend protocol.")
122 :documentation
"Internal backend data.")
123 (create-function :initarg
:create-function
127 :documentation
"The create function.")
128 (search-function :initarg
:search-function
132 :documentation
"The search function.")))
134 (defcustom auth-source-protocols
'((imap "imap" "imaps" "143" "993")
135 (pop3 "pop3" "pop" "pop3s" "110" "995")
139 "List of authentication protocols and their names"
142 :version
"23.2" ;; No Gnus
143 :type
'(repeat :tag
"Authentication Protocols"
144 (cons :tag
"Protocol Entry"
145 (symbol :tag
"Protocol")
147 (string :tag
"Name")))))
149 ;; Generate all the protocols in a format Customize can use.
150 ;; TODO: generate on the fly from auth-source-protocols
151 (defconst auth-source-protocols-customize
153 (let ((p (car-safe a
)))
155 :tag
(upcase (symbol-name p
))
157 auth-source-protocols
))
159 (defvar auth-source-creation-defaults nil
160 ;; FIXME: AFAICT this is not set (or let-bound) anywhere!
161 "Defaults for creating token values. Usually let-bound.")
163 (defvar auth-source-creation-prompts nil
164 "Default prompts for token values. Usually let-bound.")
166 (make-obsolete 'auth-source-hide-passwords nil
"Emacs 24.1")
168 (defcustom auth-source-save-behavior
'ask
169 "If set, auth-source will respect it for save behavior."
171 :version
"23.2" ;; No Gnus
173 :tag
"auth-source new token save behavior"
174 (const :tag
"Always save" t
)
175 (const :tag
"Never save" nil
)
176 (const :tag
"Ask" ask
)))
178 ;; TODO: make the default (setq auth-source-netrc-use-gpg-tokens `((,(if (boundp 'epa-file-auto-mode-alist-entry) (car epa-file-auto-mode-alist-entry) "\\.gpg\\'") never) (t gpg)))
179 ;; TODO: or maybe leave as (setq auth-source-netrc-use-gpg-tokens 'never)
181 (defcustom auth-source-netrc-use-gpg-tokens
'never
182 "Set this to tell auth-source when to create GPG password
183 tokens in netrc files. It's either an alist or `never'.
184 Note that if EPA/EPG is not available, this should NOT be used."
186 :version
"23.2" ;; No Gnus
188 (const :tag
"Always use GPG password tokens" (t gpg
))
189 (const :tag
"Never use GPG password tokens" never
)
190 (repeat :tag
"Use a lookup list"
192 (choice :tag
"Matcher"
193 (const :tag
"Match anything" t
)
194 (const :tag
"The EPA encrypted file extensions"
195 ,(if (boundp 'epa-file-auto-mode-alist-entry
)
196 (car epa-file-auto-mode-alist-entry
)
198 (regexp :tag
"Regular expression"))
199 (choice :tag
"What to do"
200 (const :tag
"Save GPG-encrypted password tokens" gpg
)
201 (const :tag
"Don't encrypt tokens" never
))))))
203 (defcustom auth-source-do-cache t
204 "Whether auth-source should cache information with `password-cache'."
206 :version
"23.2" ;; No Gnus
209 (defcustom auth-source-debug nil
210 "Whether auth-source should log debug messages.
212 If the value is nil, debug messages are not logged.
214 If the value is t, debug messages are logged with `message'. In
215 that case, your authentication data will be in the clear (except
218 If the value is a function, debug messages are logged by calling
219 that function using the same arguments as `message'."
221 :version
"23.2" ;; No Gnus
223 :tag
"auth-source debugging mode"
224 (const :tag
"Log using `message' to the *Messages* buffer" t
)
225 (const :tag
"Log all trivia with `message' to the *Messages* buffer"
227 (function :tag
"Function that takes arguments like `message'")
228 (const :tag
"Don't log anything" nil
)))
230 (defcustom auth-sources
'("~/.authinfo" "~/.authinfo.gpg" "~/.netrc")
231 "List of authentication sources.
232 Each entry is the authentication type with optional properties.
233 Entries are tried in the order in which they appear.
234 See Info node `(auth)Help for users' for details.
236 If an entry names a file with the \".gpg\" extension and you have
237 EPA/EPG set up, the file will be encrypted and decrypted
238 automatically. See Info node `(epa)Encrypting/decrypting gpg files'
241 It's best to customize this with `\\[customize-variable]' because the choices
242 can get pretty complex."
244 :version
"26.1" ;; No Gnus
245 :type
`(repeat :tag
"Authentication Sources"
247 (string :tag
"Just a file")
248 (const :tag
"Default Secrets API Collection" default
)
249 (const :tag
"Login Secrets API Collection" "secrets:Login")
250 (const :tag
"Temp Secrets API Collection" "secrets:session")
252 (const :tag
"Default internet Mac OS Keychain"
253 macos-keychain-internet
)
255 (const :tag
"Default generic Mac OS Keychain"
256 macos-keychain-generic
)
258 (list :tag
"Source definition"
259 (const :format
"" :value
:source
)
260 (choice :tag
"Authentication backend choice"
261 (string :tag
"Authentication Source (file)")
263 :tag
"Secret Service API/KWallet/GNOME Keyring"
264 (const :format
"" :value
:secrets
)
265 (choice :tag
"Collection to use"
266 (string :tag
"Collection name")
267 (const :tag
"Default" default
)
268 (const :tag
"Login" "Login")
270 :tag
"Temporary" "session")))
272 :tag
"Mac OS internet Keychain"
274 :value
:macos-keychain-internet
)
275 (choice :tag
"Collection to use"
276 (string :tag
"internet Keychain path")
277 (const :tag
"default" default
)))
279 :tag
"Mac OS generic Keychain"
281 :value
:macos-keychain-generic
)
282 (choice :tag
"Collection to use"
283 (string :tag
"generic Keychain path")
284 (const :tag
"default" default
))))
285 (repeat :tag
"Extra Parameters" :inline t
286 (choice :tag
"Extra parameter"
289 (const :format
"" :value
:host
)
290 (choice :tag
"Host (machine) choice"
293 :tag
"Regular expression")))
296 (const :format
"" :value
:port
)
300 ,@auth-source-protocols-customize
))
301 (list :tag
"User" :inline t
302 (const :format
"" :value
:user
)
304 :tag
"Personality/Username"
308 (sexp :tag
"A data structure (external provider)"))))
310 (defcustom auth-source-gpg-encrypt-to t
311 "List of recipient keys that `authinfo.gpg' encrypted to.
312 If the value is not a list, symmetric encryption will be used."
314 :version
"24.1" ;; No Gnus
315 :type
'(choice (const :tag
"Symmetric encryption" t
)
316 (repeat :tag
"Recipient public keys"
317 (string :tag
"Recipient public key"))))
319 (defun auth-source-do-debug (&rest msg
)
320 (when auth-source-debug
321 (apply #'auth-source-do-warn msg
)))
323 (defun auth-source-do-trivia (&rest msg
)
324 (when (or (eq auth-source-debug
'trivia
)
325 (functionp auth-source-debug
))
326 (apply #'auth-source-do-warn msg
)))
328 (defun auth-source-do-warn (&rest msg
)
330 ;; set logger to either the function in auth-source-debug or 'message
331 ;; note that it will be 'message if auth-source-debug is nil
332 (if (functionp auth-source-debug
)
337 (defun auth-source-read-char-choice (prompt choices
)
338 "Read one of CHOICES by `read-char-choice', or `read-char'.
339 `dropdown-list' support is disabled because it doesn't work reliably.
340 Only one of CHOICES will be returned. The PROMPT is augmented
341 with \"[a/b/c] \" if CHOICES is \(?a ?b ?c)."
343 (let* ((prompt-choices
345 (cl-loop for c in choices collect
(format "%c/" c
))))
346 (prompt-choices (concat "[" (substring prompt-choices
0 -
1) "] "))
347 (full-prompt (concat prompt prompt-choices
))
350 (while (not (memq k choices
))
351 (setq k
(read-char-choice full-prompt choices
)))
354 (defvar auth-source-backend-parser-functions nil
355 "List of auth-source parser functions.
356 Each function takes an entry from `auth-sources' as parameter and
357 returns a backend or nil if the entry is not supported. Add a
358 parser function to this list with `add-hook'. Searching for a
359 backend starts with the first element on the list and stops as
360 soon as a function returns non-nil.")
362 (defun auth-source-backend-parse (entry)
363 "Create an auth-source-backend from an ENTRY in `auth-sources'."
366 (cl-dolist (f auth-source-backend-parser-functions
)
367 (when (setq backend
(funcall f entry
))
371 ;; none of the parsers worked
373 "auth-source-backend-parse: invalid backend spec: %S" entry
)
374 (setq backend
(make-instance 'auth-source-backend
377 (auth-source-backend-parse-parameters entry backend
)))
379 (defun auth-source-backends-parser-file (entry)
380 ;; take just a file name use it as a netrc/plist file
381 ;; matching any user, host, and protocol
382 (when (stringp entry
)
383 (setq entry
`(:source
,entry
)))
385 ;; a file name with parameters
386 ((stringp (plist-get entry
:source
))
387 (if (equal (file-name-extension (plist-get entry
:source
)) "plist")
389 (plist-get entry
:source
)
390 :source
(plist-get entry
:source
)
392 :search-function
#'auth-source-plstore-search
393 :create-function
#'auth-source-plstore-create
394 :data
(plstore-open (plist-get entry
:source
)))
396 (plist-get entry
:source
)
397 :source
(plist-get entry
:source
)
399 :search-function
#'auth-source-netrc-search
400 :create-function
#'auth-source-netrc-create
)))))
402 ;; Note this function should be last in the parser functions, so we add it first
403 (add-hook 'auth-source-backend-parser-functions
'auth-source-backends-parser-file
)
405 (defun auth-source-backends-parser-macos-keychain (entry)
406 ;; take macos-keychain-{internet,generic}:XYZ and use it as macOS
407 ;; Keychain "XYZ" matching any user, host, and protocol
408 (when (and (stringp entry
) (string-match "^macos-keychain-internet:\\(.+\\)"
410 (setq entry
`(:source
(:macos-keychain-internet
411 ,(match-string 1 entry
)))))
412 (when (and (stringp entry
) (string-match "^macos-keychain-generic:\\(.+\\)"
414 (setq entry
`(:source
(:macos-keychain-generic
415 ,(match-string 1 entry
)))))
416 ;; take 'macos-keychain-internet or generic and use it as a Mac OS
417 ;; Keychain collection matching any user, host, and protocol
418 (when (eq entry
'macos-keychain-internet
)
419 (setq entry
'(:source
(:macos-keychain-internet default
))))
420 (when (eq entry
'macos-keychain-generic
)
421 (setq entry
'(:source
(:macos-keychain-generic default
))))
423 ;; the macOS Keychain
425 (not (null (plist-get entry
:source
))) ; the source must not be nil
426 (listp (plist-get entry
:source
)) ; and it must be a list
428 (plist-get (plist-get entry
:source
) :macos-keychain-generic
)
429 (plist-get (plist-get entry
:source
) :macos-keychain-internet
)))
431 (let* ((source-spec (plist-get entry
:source
))
432 (keychain-generic (plist-get source-spec
:macos-keychain-generic
))
433 (keychain-type (if keychain-generic
434 'macos-keychain-generic
435 'macos-keychain-internet
))
436 (source (plist-get source-spec
(if keychain-generic
437 :macos-keychain-generic
438 :macos-keychain-internet
))))
440 (when (symbolp source
)
441 (setq source
(symbol-name source
)))
444 (format "Mac OS Keychain (%s)" source
)
447 :search-function
#'auth-source-macos-keychain-search
448 :create-function
#'auth-source-macos-keychain-create
)))))
450 (add-hook 'auth-source-backend-parser-functions
'auth-source-backends-parser-macos-keychain
)
452 (defun auth-source-backends-parser-secrets (entry)
453 ;; take secrets:XYZ and use it as Secrets API collection "XYZ"
454 ;; matching any user, host, and protocol
455 (when (and (stringp entry
) (string-match "^secrets:\\(.+\\)" entry
))
456 (setq entry
`(:source
(:secrets
,(match-string 1 entry
)))))
457 ;; take 'default and use it as a Secrets API default collection
458 ;; matching any user, host, and protocol
459 (when (eq entry
'default
)
460 (setq entry
'(:source
(:secrets default
))))
462 ;; the Secrets API. We require the package, in order to have a
463 ;; defined value for `secrets-enabled'.
465 (not (null (plist-get entry
:source
))) ; the source must not be nil
466 (listp (plist-get entry
:source
)) ; and it must be a list
467 (not (null (plist-get
468 (plist-get entry
:source
)
469 :secrets
))) ; the source must have :secrets
470 (require 'secrets nil t
) ; and we must load the Secrets API
471 secrets-enabled
) ; and that API must be enabled
473 ;; the source is either the :secrets key in ENTRY or
474 ;; if that's missing or nil, it's "session"
475 (let ((source (plist-get (plist-get entry
:source
) :secrets
)))
477 ;; if the source is a symbol, we look for the alias named so,
478 ;; and if that alias is missing, we use "Login"
479 (when (symbolp source
)
480 (setq source
(or (secrets-get-alias (symbol-name source
))
483 (if (featurep 'secrets
)
485 (format "Secrets API (%s)" source
)
488 :search-function
#'auth-source-secrets-search
489 :create-function
#'auth-source-secrets-create
)
491 "auth-source-backend-parse: no Secrets API, ignoring spec: %S" entry
)
493 (format "Ignored Secrets API (%s)" source
)
497 (add-hook 'auth-source-backend-parser-functions
'auth-source-backends-parser-secrets
)
499 (defun auth-source-backend-parse-parameters (entry backend
)
500 "Fills in the extra auth-source-backend parameters of ENTRY.
501 Using the plist ENTRY, get the :host, :port, and :user search
503 (let ((entry (if (stringp entry
)
507 (when (setq val
(plist-get entry
:host
))
508 (oset backend host val
))
509 (when (setq val
(plist-get entry
:user
))
510 (oset backend user val
))
511 (when (setq val
(plist-get entry
:port
))
512 (oset backend port val
)))
515 ;; (mapcar 'auth-source-backend-parse auth-sources)
517 (cl-defun auth-source-search (&rest spec
518 &key max require create delete
520 "Search or modify authentication backends according to SPEC.
522 This function parses `auth-sources' for matches of the SPEC
523 plist. It can optionally create or update an authentication
524 token if requested. A token is just a standard Emacs property
525 list with a :secret property that can be a function; all the
526 other properties will always hold scalar values.
528 Typically the :secret property, if present, contains a password.
530 Common search keys are :max, :host, :port, and :user. In
531 addition, :create specifies if and how tokens will be created.
532 Finally, :type can specify which backend types you want to check.
534 A string value is always matched literally. A symbol is matched
535 as its string value, literally. All the SPEC values can be
536 single values (symbol or string) or lists thereof (in which case
537 any of the search terms matches).
539 :create t means to create a token if possible.
541 A new token will be created if no matching tokens were found.
542 The new token will have only the keys the backend requires. For
543 the netrc backend, for instance, that's the user, host, and
548 \(let ((auth-source-creation-defaults \\='((user . \"defaultUser\")
549 (A . \"default A\"))))
550 (auth-source-search :host \"mine\" :type \\='netrc :max 1
551 :P \"pppp\" :Q \"qqqq\"
556 \"Search for any entry matching host `mine' in backends of type
557 `netrc', maximum one result.
559 Create a new entry if you found none. The netrc backend will
560 automatically require host, user, and port. The host will be
561 `mine'. We prompt for the user with default `defaultUser' and
562 for the port without a default. We will not prompt for A, Q,
563 or P. The resulting token will only have keys user, host, and
566 :create \\='(A B C) also means to create a token if possible.
568 The behavior is like :create t but if the list contains any
569 parameter, that parameter will be required in the resulting
570 token. The value for that parameter will be obtained from the
571 search parameters or from user input. If any queries are needed,
572 the alist `auth-source-creation-defaults' will be checked for the
573 default value. If the user, host, or port are missing, the alist
574 `auth-source-creation-prompts' will be used to look up the
575 prompts IN THAT ORDER (so the `user' prompt will be queried first,
576 then `host', then `port', and finally `secret'). Each prompt string
577 can use %u, %h, and %p to show the user, host, and port.
581 \(let ((auth-source-creation-defaults \\='((user . \"defaultUser\")
582 (A . \"default A\")))
583 (auth-source-creation-prompts
584 \\='((password . \"Enter IMAP password for %h:%p: \"))))
585 (auth-source-search :host \\='(\"nonesuch\" \"twosuch\") :type \\='netrc :max 1
586 :P \"pppp\" :Q \"qqqq\"
587 :create \\='(A B Q)))
591 \"Search for any entry matching host `nonesuch'
592 or `twosuch' in backends of type `netrc', maximum one result.
594 Create a new entry if you found none. The netrc backend will
595 automatically require host, user, and port. The host will be
596 `nonesuch' and Q will be `qqqq'. We prompt for the password
597 with the shown prompt. We will not prompt for Q. The resulting
598 token will have keys user, host, port, A, B, and Q. It will not
599 have P with any value, even though P is used in the search to
600 find only entries that have P set to `pppp'.\"
602 When multiple values are specified in the search parameter, the
603 user is prompted for which one. So :host (X Y Z) would ask the
604 user to choose between X, Y, and Z.
606 This creation can fail if the search was not specific enough to
607 create a new token (it's up to the backend to decide that). You
608 should `catch' the backend-specific error as usual. Some
609 backends (netrc, at least) will prompt the user rather than throw
612 :require (A B C) means that only results that contain those
613 tokens will be returned. Thus for instance requiring :secret
614 will ensure that any results will actually have a :secret
617 :delete t means to delete any found entries. nil by default.
618 Use `auth-source-delete' in ELisp code instead of calling
619 `auth-source-search' directly with this parameter.
621 :type (X Y Z) will check only those backend types. `netrc' and
622 `secrets' are the only ones supported right now.
624 :max N means to try to return at most N items (defaults to 1).
625 More than N items may be returned, depending on the search and
628 When :max is 0 the function will return just t or nil to indicate
629 if any matches were found.
631 :host (X Y Z) means to match only hosts X, Y, or Z according to
632 the match rules above. Defaults to t.
634 :user (X Y Z) means to match only users X, Y, or Z according to
635 the match rules above. Defaults to t.
637 :port (P Q R) means to match only protocols P, Q, or R.
640 :K (V1 V2 V3) for any other key K will match values V1, V2, or
641 V3 (note the match rules above).
643 The return value is a list with at most :max tokens. Each token
644 is a plist with keys :backend :host :port :user, plus any other
645 keys provided by the backend (notably :secret). But note the
646 exception for :max 0, which see above.
648 The token can hold a :save-function key. If you call that, the
649 user will be prompted to save the data to the backend. You can't
650 request that this should happen right after creation, because
651 `auth-source-search' has no way of knowing if the token is
652 actually useful. So the caller must arrange to call this function.
654 The token's :secret key can hold a function. In that case you
655 must call it to obtain the actual value."
656 (let* ((backends (mapcar #'auth-source-backend-parse auth-sources
))
658 (ignored-keys '(:require
:create
:delete
:max
))
659 (keys (cl-loop for i below
(length spec
) by
2
660 unless
(memq (nth i spec
) ignored-keys
)
661 collect
(nth i spec
)))
662 (cached (auth-source-remembered-p spec
))
663 ;; note that we may have cached results but found is still nil
664 ;; (there were no results from the search)
665 (found (auth-source-recall spec
))
668 (if (and cached auth-source-do-cache
)
669 (auth-source-do-debug
670 "auth-source-search: found %d CACHED results matching %S"
674 (or (eq t create
) (listp create
)) t
675 "Invalid auth-source :create parameter (must be t or a list): %s %s")
679 "Invalid auth-source :require parameter (must be a list): %s")
681 (setq filtered-backends
(copy-sequence backends
))
682 (dolist (backend backends
)
683 (cl-dolist (key keys
)
684 ;; ignore invalid slots
686 (unless (auth-source-search-collection
688 (slot-value backend key
))
689 (setq filtered-backends
(delq backend filtered-backends
))
691 (invalid-slot-name nil
))))
693 (auth-source-do-trivia
694 "auth-source-search: found %d backends matching %S"
695 (length filtered-backends
) spec
)
697 ;; (debug spec "filtered" filtered-backends)
698 ;; First go through all the backends without :create, so we can
700 (setq found
(auth-source-search-backends filtered-backends
704 ;; create is always nil here
708 (auth-source-do-debug
709 "auth-source-search: found %d results (max %d) matching %S"
710 (length found
) max spec
)
712 ;; If we didn't find anything, then we allow the backend(s) to
713 ;; create the entries.
716 (setq found
(auth-source-search-backends filtered-backends
722 (auth-source-do-debug
723 "auth-source-search: CREATED %d results (max %d) matching %S"
724 (length found
) max spec
))
726 ;; note we remember the lack of result too, if it's applicable
727 (when auth-source-do-cache
728 (auth-source-remember spec found
)))
734 (defun auth-source-search-backends (backends spec max create delete require
)
735 (let ((max (if (zerop max
) 1 max
)) ; stop with 1 match if we're asked for zero
737 (dolist (backend backends
)
738 (when (> max
(length matches
)) ; if we need more matches...
739 (let* ((bmatches (apply
740 (slot-value backend
'search-function
)
742 :type
(slot-value backend
'type
)
743 ;; note we're overriding whatever the spec
744 ;; has for :max, :require, :create, and :delete
751 (auth-source-do-trivia
752 "auth-source-search-backend: got %d (max %d) in %s:%s matching %S"
753 (length bmatches
) max
754 (slot-value backend
'type
)
755 (slot-value backend
'source
)
757 (setq matches
(append matches bmatches
))))))
760 (defun auth-source-delete (&rest spec
)
761 "Delete entries from the authentication backends according to SPEC.
762 Calls `auth-source-search' with the :delete property in SPEC set to t.
763 The backend may not actually delete the entries.
765 Returns the deleted entries."
766 (apply #'auth-source-search
(plist-put spec
:delete t
)))
768 (defun auth-source-search-collection (collection value
)
769 "Returns t is VALUE is t or COLLECTION is t or COLLECTION contains VALUE."
770 (when (and (atom collection
) (not (eq t collection
)))
771 (setq collection
(list collection
)))
773 ;; (debug :collection collection :value value)
774 (or (eq collection t
)
776 (equal collection value
)
777 (member value collection
)))
779 (defvar auth-source-netrc-cache nil
)
781 (defun auth-source-forget-all-cached ()
782 "Forget all cached auth-source data."
784 (maphash (lambda (key _password
)
785 (when (eq 'auth-source
(car-safe key
))
787 (password-cache-remove key
)))
789 (setq auth-source-netrc-cache nil
))
791 (defun auth-source-format-cache-entry (spec)
792 "Format SPEC entry to put it in the password cache."
793 `(auth-source .
,spec
))
795 (defun auth-source-remember (spec found
)
796 "Remember FOUND search results for SPEC."
797 (let ((password-cache-expiry auth-source-cache-expiry
))
799 (auth-source-format-cache-entry spec
) found
)))
801 (defun auth-source-recall (spec)
802 "Recall FOUND search results for SPEC."
803 (password-read-from-cache (auth-source-format-cache-entry spec
)))
805 (defun auth-source-remembered-p (spec)
806 "Check if SPEC is remembered."
808 (auth-source-format-cache-entry spec
)))
810 (defun auth-source-forget (spec)
811 "Forget any cached data matching SPEC exactly.
813 This is the same SPEC you passed to `auth-source-search'.
814 Returns t or nil for forgotten or not found."
815 (password-cache-remove (auth-source-format-cache-entry spec
)))
817 (defun auth-source-forget+ (&rest spec
)
818 "Forget any cached data matching SPEC. Returns forgotten count.
820 This is not a full `auth-source-search' spec but works similarly.
821 For instance, \(:host \"myhost\" \"yourhost\") would find all the
822 cached data that was found with a search for those two hosts,
823 while \(:host t) would find all host entries."
826 (lambda (key _password
)
827 (when (and (eq 'auth-source
(car-safe key
))
828 ;; and the spec matches what was stored in the cache
829 (auth-source-specmatchp spec
(cdr key
)))
831 (password-cache-remove key
)
836 (defun auth-source-specmatchp (spec stored
)
837 (let ((keys (cl-loop for i below
(length spec
) by
2
838 collect
(nth i spec
))))
840 (cl-dolist (key keys
)
841 (unless (auth-source-search-collection (plist-get stored key
)
842 (plist-get spec key
))
846 (defun auth-source-pick-first-password (&rest spec
)
847 "Pick the first secret found from applying SPEC to `auth-source-search'."
848 (let* ((result (nth 0 (apply #'auth-source-search
(plist-put spec
:max
1))))
849 (secret (plist-get result
:secret
)))
851 (if (functionp secret
)
855 (defun auth-source-format-prompt (prompt alist
)
856 "Format PROMPT using %x (for any character x) specifiers in ALIST."
858 (let ((c (nth 0 cell
))
861 (setq prompt
(replace-regexp-in-string (format "%%%c" c
)
866 (defun auth-source-ensure-strings (values)
869 (unless (listp values
)
870 (setq values
(list values
)))
871 (mapcar (lambda (value)
877 ;;; Backend specific parsing: netrc/authinfo backend
879 (defun auth-source--aput-1 (alist key val
)
882 (while (and (consp rest
) (not (equal key
(caar rest
))))
883 (push (pop rest
) seen
))
885 (if (null rest
) alist
886 (nconc (nreverse seen
)
887 (if (equal key
(caar rest
)) (cdr rest
) rest
))))))
888 (defmacro auth-source--aput
(var key val
)
889 `(setq ,var
(auth-source--aput-1 ,var
,key
,val
)))
891 (defun auth-source--aget (alist key
)
892 (cdr (assoc key alist
)))
894 ;; (auth-source-netrc-parse :file "~/.authinfo.gpg")
895 (cl-defun auth-source-netrc-parse (&key file max host user port require
897 "Parse FILE and return a list of all entries in the file.
898 Note that the MAX parameter is used so we can exit the parse early."
900 ;; We got already parsed contents; just return it.
902 (when (file-exists-p file
)
903 (setq port
(auth-source-ensure-strings port
))
905 (let* ((max (or max
5000)) ; sanity check: default to stop at 5K
907 (cached (cdr-safe (assoc file auth-source-netrc-cache
)))
908 (cached-mtime (plist-get cached
:mtime
))
909 (cached-secrets (plist-get cached
:secret
))
910 (check (lambda(alist)
912 (auth-source-search-collection
915 (auth-source--aget alist
"machine")
916 (auth-source--aget alist
"host")
918 (auth-source-search-collection
921 (auth-source--aget alist
"login")
922 (auth-source--aget alist
"account")
923 (auth-source--aget alist
"user")
925 (auth-source-search-collection
928 (auth-source--aget alist
"port")
929 (auth-source--aget alist
"protocol")
932 ;; the required list of keys is nil, or
934 ;; every element of require is in n (normalized)
935 (let ((n (nth 0 (auth-source-netrc-normalize
936 (list alist
) file
))))
937 (cl-loop for req in require
938 always
(plist-get n req
)))))))
941 (if (and (functionp cached-secrets
)
943 (nth 5 (file-attributes file
))))
945 (auth-source-do-trivia
946 "auth-source-netrc-parse: using CACHED file data for %s"
948 (insert (funcall cached-secrets
)))
949 (insert-file-contents file
)
950 ;; cache all netrc files (used to be just .gpg files)
951 ;; Store the contents of the file heavily encrypted in memory.
952 ;; (note for the irony-impaired: they are just obfuscated)
954 auth-source-netrc-cache file
955 (list :mtime
(nth 5 (file-attributes file
))
956 :secret
(let ((v (mapcar #'1+ (buffer-string))))
957 (lambda () (apply #'string
(mapcar #'1- v
)))))))
958 (goto-char (point-min))
959 (let ((entries (auth-source-netrc-parse-entries check max
))
961 (while (setq alist
(pop entries
))
962 (push (nreverse alist
) result
)))
965 (when auth-source-gpg-encrypt-to
966 ;; (see bug#7487) making `epa-file-encrypt-to' local to
967 ;; this buffer lets epa-file skip the key selection query
968 ;; (see the `local-variable-p' check in
969 ;; `epa-file-write-region').
970 (unless (local-variable-p 'epa-file-encrypt-to
(current-buffer))
971 (make-local-variable 'epa-file-encrypt-to
))
972 (if (listp auth-source-gpg-encrypt-to
)
973 (setq epa-file-encrypt-to auth-source-gpg-encrypt-to
)))
975 ;; ask AFTER we've successfully opened the file
976 (when (y-or-n-p (format "Save file %s? (%d deletions)"
978 (write-region (point-min) (point-max) file nil
'silent
)
979 (auth-source-do-debug
980 "auth-source-netrc-parse: modified %d lines in %s"
983 (nreverse result
))))))
985 (defun auth-source-netrc-parse-next-interesting ()
986 "Advance to the next interesting position in the current buffer."
987 ;; If we're looking at a comment or are at the end of the line, move forward
988 (while (or (looking-at "#")
992 (skip-chars-forward "\t "))
994 (defun auth-source-netrc-parse-one ()
995 "Read one thing from the current buffer."
996 (auth-source-netrc-parse-next-interesting)
998 (when (or (looking-at "'\\([^']*\\)'")
999 (looking-at "\"\\([^\"]*\\)\"")
1000 (looking-at "\\([^ \t\n]+\\)"))
1001 (forward-char (length (match-string 0)))
1002 (auth-source-netrc-parse-next-interesting)
1003 (match-string-no-properties 1)))
1005 ;; with thanks to org-mode
1006 (defsubst auth-source-current-line
(&optional pos
)
1008 (and pos
(goto-char pos
))
1009 ;; works also in narrowed buffer, because we start at 1, not point-min
1010 (+ (if (bolp) 1 0) (count-lines 1 (point)))))
1012 (defun auth-source-netrc-parse-entries(check max
)
1013 "Parse up to MAX netrc entries, passed by CHECK, from the current buffer."
1014 (let ((adder (lambda(check alist all
)
1017 (> max
(length all
))
1018 (funcall check alist
))
1021 item item2 all alist default
)
1022 (while (setq item
(auth-source-netrc-parse-one))
1023 (setq default
(equal item
"default"))
1024 ;; We're starting a new machine. Save the old one.
1027 (equal item
"machine")))
1028 ;; (auth-source-do-trivia
1029 ;; "auth-source-netrc-parse-entries: got entry %S" alist)
1030 (setq all
(funcall adder check alist all
)
1032 ;; In default entries, we don't have a next token.
1033 ;; We store them as ("machine" . t)
1035 (push (cons "machine" t
) alist
)
1036 ;; Not a default entry. Grab the next item.
1037 (when (setq item2
(auth-source-netrc-parse-one))
1038 ;; Did we get a "machine" value?
1039 (if (equal item2
"machine")
1041 "%s: Unexpected `machine' token at line %d"
1042 "auth-source-netrc-parse-entries"
1043 (auth-source-current-line))
1044 (push (cons item item2
) alist
)))))
1046 ;; Clean up: if there's an entry left over, use it.
1048 (setq all
(funcall adder check alist all
))
1049 ;; (auth-source-do-trivia
1050 ;; "auth-source-netrc-parse-entries: got2 entry %S" alist)
1054 (defvar auth-source-passphrase-alist nil
)
1056 (defun auth-source-token-passphrase-callback-function (_context _key-id file
)
1057 (let* ((file (file-truename file
))
1058 (entry (assoc file auth-source-passphrase-alist
))
1060 ;; return the saved passphrase, calling a function if needed
1061 (or (copy-sequence (if (functionp (cdr entry
))
1062 (funcall (cdr entry
))
1066 (setq entry
(list file
))
1067 (push entry auth-source-passphrase-alist
))
1070 (format "Passphrase for %s tokens: " file
)
1072 (setcdr entry
(let ((p (copy-sequence passphrase
)))
1076 (defun auth-source-epa-extract-gpg-token (secret file
)
1077 "Pass either the decoded SECRET or the gpg:BASE64DATA version.
1078 FILE is the file from which we obtained this token."
1079 (when (string-match "^gpg:\\(.+\\)" secret
)
1080 (setq secret
(base64-decode-string (match-string 1 secret
))))
1081 (let ((context (epg-make-context 'OpenPGP
)))
1082 (epg-context-set-passphrase-callback
1084 (cons #'auth-source-token-passphrase-callback-function
1086 (epg-decrypt-string context secret
)))
1088 (defvar pp-escape-newlines
)
1090 (defun auth-source-epa-make-gpg-token (secret file
)
1091 (let ((context (epg-make-context 'OpenPGP
))
1092 (pp-escape-newlines nil
)
1094 (setf (epg-context-armor context
) t
)
1095 (epg-context-set-passphrase-callback
1097 (cons #'auth-source-token-passphrase-callback-function
1099 (setq cipher
(epg-encrypt-string context secret nil
))
1102 (base64-encode-region (point-min) (point-max) t
)
1103 (concat "gpg:" (buffer-substring-no-properties
1107 (defun auth-source--symbol-keyword (symbol)
1108 (intern (format ":%s" symbol
)))
1110 (defun auth-source-netrc-normalize (alist filename
)
1111 (mapcar (lambda (entry)
1113 (while (setq item
(pop entry
))
1114 (let ((k (car item
))
1117 ;; apply key aliases
1118 (setq k
(cond ((member k
'("machine")) "host")
1119 ((member k
'("login" "account")) "user")
1120 ((member k
'("protocol")) "port")
1121 ((member k
'("password")) "secret")
1124 ;; send back the secret in a function (lexical binding)
1125 (when (equal k
"secret")
1126 (setq v
(let ((lexv v
)
1127 (token-decoder nil
))
1128 (when (string-match "^gpg:" lexv
)
1129 ;; it's a GPG token: create a token decoder
1130 ;; which unsets itself once
1134 (auth-source-epa-extract-gpg-token
1137 (setq token-decoder nil
)))))
1140 (setq lexv
(funcall token-decoder lexv
)))
1142 (setq ret
(plist-put ret
1143 (auth-source--symbol-keyword k
)
1148 (cl-defun auth-source-netrc-search (&rest spec
1149 &key backend require create
1150 type max host user port
1152 "Given a property list SPEC, return search matches from the :backend.
1153 See `auth-source-search' for details on SPEC."
1154 ;; just in case, check that the type is correct (null or same as the backend)
1155 (cl-assert (or (null type
) (eq type
(oref backend type
)))
1156 t
"Invalid netrc search: %s %s")
1158 (let ((results (auth-source-netrc-normalize
1159 (auth-source-netrc-parse
1162 :file
(oref backend source
)
1166 (oref backend source
))))
1168 ;; if we need to create an entry AND none were found to match
1172 ;; create based on the spec and record the value
1174 ;; if the user did not want to create the entry
1175 ;; in the file, it will be returned
1176 (apply (slot-value backend
'create-function
) spec
)
1177 ;; if not, we do the search again without :create
1178 ;; to get the updated data.
1180 ;; the result will be returned, even if the search fails
1181 (apply #'auth-source-netrc-search
1182 (plist-put spec
:create nil
)))))
1185 (defun auth-source-netrc-element-or-first (v)
1190 ;; (auth-source-search :host "nonesuch" :type 'netrc :max 1 :create t)
1191 ;; (auth-source-search :host "nonesuch" :type 'netrc :max 1 :create t :create-extra-keys '((A "default A") (B)))
1193 (cl-defun auth-source-netrc-create (&rest spec
1194 &key backend host port create
1196 (let* ((base-required '(host user port secret
))
1197 ;; we know (because of an assertion in auth-source-search) that the
1198 ;; :create parameter is either t or a list (which includes nil)
1199 (create-extra (if (eq t create
) nil create
))
1200 (current-data (car (auth-source-search :max
1
1203 (required (append base-required create-extra
))
1204 (file (oref backend source
))
1206 ;; `valist' is an alist
1208 ;; `artificial' will be returned if no creation is needed
1211 ;; only for base required elements (defined as function parameters):
1212 ;; fill in the valist with whatever data we may have from the search
1213 ;; we complete the first value if it's a list and use the value otherwise
1214 (dolist (br base-required
)
1215 (let ((val (plist-get spec
(auth-source--symbol-keyword br
))))
1217 (let ((br-choice (cond
1218 ;; all-accepting choice (predicate is t)
1220 ;; just the value otherwise
1223 (auth-source--aput valist br br-choice
))))))
1225 ;; for extra required elements, see if the spec includes a value for them
1226 (dolist (er create-extra
)
1227 (let ((k (auth-source--symbol-keyword er
))
1228 (keys (cl-loop for i below
(length spec
) by
2
1229 collect
(nth i spec
))))
1231 (auth-source--aput valist er
(plist-get spec k
)))))
1233 ;; for each required element
1234 (dolist (r required
)
1235 (let* ((data (auth-source--aget valist r
))
1236 ;; take the first element if the data is a list
1237 (data (or (auth-source-netrc-element-or-first data
)
1238 (plist-get current-data
1239 (auth-source--symbol-keyword r
))))
1240 ;; this is the default to be offered
1241 (given-default (auth-source--aget
1242 auth-source-creation-defaults r
))
1243 ;; the default supplementals are simple:
1244 ;; for the user, try `given-default' and then (user-login-name);
1245 ;; otherwise take `given-default'
1247 ((and (not given-default
) (eq r
'user
))
1250 (printable-defaults (list
1253 (auth-source-netrc-element-or-first
1254 (auth-source--aget valist
'user
))
1255 (plist-get artificial
:user
)
1259 (auth-source-netrc-element-or-first
1260 (auth-source--aget valist
'host
))
1261 (plist-get artificial
:host
)
1265 (auth-source-netrc-element-or-first
1266 (auth-source--aget valist
'port
))
1267 (plist-get artificial
:port
)
1269 (prompt (or (auth-source--aget auth-source-creation-prompts r
)
1271 (secret "%p password for %u@%h: ")
1272 (user "%p user name for %h: ")
1273 (host "%p host name for user %u: ")
1274 (port "%p port for %u@%h: "))
1275 (format "Enter %s (%%u@%%h:%%p): " r
)))
1276 (prompt (auth-source-format-prompt
1278 `((?u
,(auth-source--aget printable-defaults
'user
))
1279 (?h
,(auth-source--aget printable-defaults
'host
))
1280 (?p
,(auth-source--aget printable-defaults
'port
))))))
1282 ;; Store the data, prompting for the password if needed.
1285 ;; Special case prompt for passwords.
1286 ;; 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)))
1287 ;; TODO: or maybe leave as (setq auth-source-netrc-use-gpg-tokens 'never)
1288 (let* ((ep (format "Use GPG password tokens in %s?" file
))
1291 ((eq auth-source-netrc-use-gpg-tokens
'never
)
1293 ((listp auth-source-netrc-use-gpg-tokens
)
1294 (let ((check (copy-sequence
1295 auth-source-netrc-use-gpg-tokens
))
1298 (setq item
(pop check
))
1299 (when (or (eq (car item
) t
)
1300 (string-match (car item
) file
))
1301 (setq ret
(cdr item
))
1303 ;; FIXME: `ret' unused.
1304 ;; Should we return it here?
1307 (plain (or (eval default
) (read-passwd prompt
))))
1308 ;; ask if we don't know what to do (in which case
1309 ;; auth-source-netrc-use-gpg-tokens must be a list)
1311 (setq gpg-encrypt
(if (y-or-n-p ep
) 'gpg
'never
))
1312 ;; TODO: save the defcustom now? or ask?
1313 (setq auth-source-netrc-use-gpg-tokens
1314 (cons `(,file
,gpg-encrypt
)
1315 auth-source-netrc-use-gpg-tokens
)))
1316 (if (eq gpg-encrypt
'gpg
)
1317 (auth-source-epa-make-gpg-token plain file
)
1319 (if (stringp default
)
1320 (read-string (if (string-match ": *\\'" prompt
)
1321 (concat (substring prompt
0 (match-beginning 0))
1322 " (default " default
"): ")
1323 (concat prompt
"(default " default
") "))
1328 (setq artificial
(plist-put artificial
1329 (auth-source--symbol-keyword r
)
1335 ;; When r is not an empty string...
1336 (when (and (stringp data
)
1337 (< 0 (length data
)))
1338 ;; this function is not strictly necessary but I think it
1339 ;; makes the code clearer -tzz
1340 (let ((printer (lambda ()
1341 ;; append the key (the symbol name of r)
1342 ;; and the value in r
1345 (if (zerop (length add
)) "" " ")
1346 ;; remap auth-source tokens to netrc
1351 (port "port") ; redundant but clearer
1352 (t (symbol-name r
)))
1353 (if (string-match "[\"# ]" data
)
1356 (setq add
(concat add
(funcall printer
)))))))
1363 (lambda () (auth-source-netrc-saver file add
))))
1367 (defun auth-source-netrc-saver (file add
)
1368 "Save a line ADD in FILE, prompting along the way.
1369 Respects `auth-source-save-behavior'. Uses
1370 `auth-source-netrc-cache' to avoid prompting more than once."
1371 (let* ((key (format "%s %s" file
(rfc2104-hash 'md5
64 16 file add
)))
1372 (cached (assoc key auth-source-netrc-cache
)))
1375 (auth-source-do-trivia
1376 "auth-source-netrc-saver: found previous run for key %s, returning"
1379 (when (file-exists-p file
)
1380 (insert-file-contents file
))
1381 (when auth-source-gpg-encrypt-to
1382 ;; (see bug#7487) making `epa-file-encrypt-to' local to
1383 ;; this buffer lets epa-file skip the key selection query
1384 ;; (see the `local-variable-p' check in
1385 ;; `epa-file-write-region').
1386 (unless (local-variable-p 'epa-file-encrypt-to
(current-buffer))
1387 (make-local-variable 'epa-file-encrypt-to
))
1388 (if (listp auth-source-gpg-encrypt-to
)
1389 (setq epa-file-encrypt-to auth-source-gpg-encrypt-to
)))
1390 ;; we want the new data to be found first, so insert at beginning
1391 (goto-char (point-min))
1393 ;; Ask AFTER we've successfully opened the file.
1394 (let ((prompt (format "Save auth info to file %s? " file
))
1395 (done (not (eq auth-source-save-behavior
'ask
)))
1396 (bufname "*auth-source Help*")
1399 (setq k
(auth-source-read-char-choice prompt
'(?y ?n ?N ?e ??
)))
1403 (with-output-to-temp-buffer bufname
1405 (concat "(y)es, save\n"
1406 "(n)o but use the info\n"
1407 "(N)o and don't ask to save again\n"
1409 "(?) for help as you can see.\n"))
1410 ;; Why? Doesn't with-output-to-temp-buffer already do
1411 ;; the exact same thing anyway? --Stef
1412 (set-buffer standard-output
)
1419 (customize-save-variable 'auth-source-save-behavior nil
))
1420 (?e
(setq add
(read-string "Line to add: " add
)))
1423 (when (get-buffer-window bufname
)
1424 (delete-window (get-buffer-window bufname
)))
1426 ;; Make sure the info is not saved.
1427 (when (null auth-source-save-behavior
)
1430 (when (< 0 (length add
))
1435 (write-region (point-min) (point-max) file nil
'silent
)
1436 ;; Make the .authinfo file non-world-readable.
1437 (set-file-modes file
#o600
)
1438 (auth-source-do-debug
1439 "auth-source-netrc-create: wrote 1 new line to %s"
1441 (message "Saved new authentication information to %s" file
)
1443 (auth-source--aput auth-source-netrc-cache key
"ran"))))
1445 ;;; Backend specific parsing: Secrets API backend
1447 (defun auth-source-secrets-listify-pattern (pattern)
1448 "Convert a pattern with lists to a list of string patterns.
1450 auth-source patterns can have values of the form :foo (\"bar\"
1451 \"qux\"), which means to match any secret with :foo equal to
1452 \"bar\" or :foo equal to \"qux\". The secrets backend supports
1453 only string values for patterns, so this routine returns a list
1454 of patterns that is equivalent to the single original pattern
1455 when interpreted such that if a secret matches any pattern in the
1456 list, it matches the original pattern."
1459 (let* ((key (pop pattern
))
1460 (value (pop pattern
))
1461 (tails (auth-source-secrets-listify-pattern pattern
))
1462 (heads (if (stringp value
)
1463 (list (list key value
))
1464 (mapcar (lambda (v) (list key v
)) value
))))
1465 (cl-loop for h in heads
1466 nconc
(cl-loop for tl in tails collect
(append h tl
))))))
1468 (cl-defun auth-source-secrets-search (&rest spec
1469 &key backend create delete label max
1471 "Search the Secrets API; spec is like `auth-source'.
1473 The :label key specifies the item's label. It is the only key
1474 that can specify a substring. Any :label value besides a string
1475 will allow any label.
1477 All other search keys must match exactly. If you need substring
1478 matching, do a wider search and narrow it down yourself.
1480 You'll get back all the properties of the token as a plist.
1482 Here's an example that looks for the first item in the `Login'
1485 (let ((auth-sources \\='(\"secrets:Login\")))
1486 (auth-source-search :max 1)
1488 Here's another that looks for the first item in the `Login'
1489 Secrets collection whose label contains `gnus':
1491 (let ((auth-sources \\='(\"secrets:Login\")))
1492 (auth-source-search :max 1 :label \"gnus\")
1494 And this one looks for the first item in the `Login' Secrets
1495 collection that's a Google Chrome entry for the git.gnus.org site
1496 authentication tokens:
1498 (let ((auth-sources \\='(\"secrets:Login\")))
1499 (auth-source-search :max 1 :signon_realm \"https://git.gnus.org/Git\"))
1503 (cl-assert (not create
) nil
1504 "The Secrets API auth-source backend doesn't support creation yet")
1506 ;; (secrets-delete-item coll elt)
1507 (cl-assert (not delete
) nil
1508 "The Secrets API auth-source backend doesn't support deletion yet")
1510 (let* ((coll (oref backend source
))
1511 (max (or max
5000)) ; sanity check: default to stop at 5K
1512 (ignored-keys '(:create
:delete
:max
:backend
:label
:require
:type
))
1513 (search-keys (cl-loop for i below
(length spec
) by
2
1514 unless
(memq (nth i spec
) ignored-keys
)
1515 collect
(nth i spec
)))
1516 ;; build a search spec without the ignored keys
1517 ;; if a search key is nil or t (match anything), we skip it
1518 (search-specs (auth-source-secrets-listify-pattern
1519 (apply #'append
(mapcar
1521 (if (or (null (plist-get spec k
))
1522 (eq t
(plist-get spec k
)))
1524 (list k
(plist-get spec k
))))
1526 ;; needed keys (always including host, login, port, and secret)
1527 (returned-keys (delete-dups (append
1528 '(:host
:login
:port
:secret
)
1532 for search-spec in search-specs
1534 (cl-loop for item in
(apply #'secrets-search-items coll search-spec
)
1535 unless
(and (stringp label
)
1536 (not (string-match label item
)))
1538 ;; TODO: respect max in `secrets-search-items', not after the fact
1539 (items (butlast items
(- (length items
) max
)))
1540 ;; convert the item name to a full plist
1541 (items (mapcar (lambda (item)
1543 ;; make an entry for the secret (password) element
1546 (let ((v (secrets-get-secret coll item
)))
1548 ;; rewrite the entry from ((k1 v1) (k2 v2)) to plist
1550 (mapcar (lambda (entry)
1551 (list (car entry
) (cdr entry
)))
1552 (secrets-get-attributes coll item
)))))
1554 ;; ensure each item has each key in `returned-keys'
1555 (items (mapcar (lambda (plist)
1558 (mapcar (lambda (req)
1559 (if (plist-get plist req
)
1567 (defun auth-source-secrets-create (&rest spec
)
1569 ;; (apply 'secrets-create-item (auth-get-source entry) name passwd spec)
1572 ;;; Backend specific parsing: Mac OS Keychain (using /usr/bin/security) backend
1574 (cl-defun auth-source-macos-keychain-search (&rest spec
1575 &key backend create delete type max
1577 "Search the macOS Keychain; spec is like `auth-source'.
1579 All search keys must match exactly. If you need substring
1580 matching, do a wider search and narrow it down yourself.
1582 You'll get back all the properties of the token as a plist.
1584 The :type key is either `macos-keychain-internet' or
1585 `macos-keychain-generic'.
1587 For the internet keychain type, the :label key searches the
1588 item's labels (\"-l LABEL\" passed to \"/usr/bin/security\").
1589 Similarly, :host maps to \"-s HOST\", :user maps to \"-a USER\",
1590 and :port maps to \"-P PORT\" or \"-r PROT\"
1591 \(note PROT has to be a 4-character string).
1593 For the generic keychain type, the :label key searches the item's
1594 labels (\"-l LABEL\" passed to \"/usr/bin/security\").
1595 Similarly, :host maps to \"-c HOST\" (the \"creator\" keychain
1596 field), :user maps to \"-a USER\", and :port maps to \"-s PORT\".
1598 Here's an example that looks for the first item in the default
1599 generic macOS Keychain:
1601 (let ((auth-sources \\='(macos-keychain-generic)))
1602 (auth-source-search :max 1)
1604 Here's another that looks for the first item in the internet
1605 macOS Keychain collection whose label is `gnus':
1607 (let ((auth-sources \\='(macos-keychain-internet)))
1608 (auth-source-search :max 1 :label \"gnus\")
1610 And this one looks for the first item in the internet keychain
1611 entries for git.gnus.org:
1613 (let ((auth-sources \\='(macos-keychain-internet\")))
1614 (auth-source-search :max 1 :host \"git.gnus.org\"))
1617 (cl-assert (not create
) nil
1618 "The macOS Keychain auth-source backend doesn't support creation yet")
1620 ;; (macos-keychain-delete-item coll elt)
1621 (cl-assert (not delete
) nil
1622 "The macOS Keychain auth-source backend doesn't support deletion yet")
1624 (let* ((coll (oref backend source
))
1625 (max (or max
5000)) ; sanity check: default to stop at 5K
1626 ;; Filter out ignored keys from the spec
1627 (ignored-keys '(:create
:delete
:max
:backend
:label
:host
:port
))
1628 ;; Build a search spec without the ignored keys
1629 ;; FIXME make this loop a function? it's used in at least 3 places
1630 (search-keys (cl-loop for i below
(length spec
) by
2
1631 unless
(memq (nth i spec
) ignored-keys
)
1632 collect
(nth i spec
)))
1633 ;; If a search key value is nil or t (match anything), we skip it
1634 (search-spec (apply #'append
(mapcar
1636 (if (or (null (plist-get spec k
))
1637 (eq t
(plist-get spec k
)))
1639 (list k
(plist-get spec k
))))
1641 ;; needed keys (always including host, login, port, and secret)
1642 (returned-keys (delete-dups (append
1643 '(:host
:login
:port
:secret
)
1645 ;; Extract host and port from spec
1646 (hosts (plist-get spec
:host
))
1647 (hosts (if (and hosts
(listp hosts
)) hosts
`(,hosts
)))
1648 (ports (plist-get spec
:port
))
1649 (ports (if (and ports
(listp ports
)) ports
`(,ports
)))
1650 ;; Loop through all combinations of host/port and pass each of these to
1651 ;; auth-source-macos-keychain-search-items
1652 (items (catch 'match
1653 (dolist (host hosts
)
1654 (dolist (port ports
)
1655 (let* ((port (if port
(format "%S" port
)))
1656 (items (apply #'auth-source-macos-keychain-search-items
1663 (throw 'match items
)))))))
1665 ;; ensure each item has each key in `returned-keys'
1666 (items (mapcar (lambda (plist)
1669 (mapcar (lambda (req)
1670 (if (plist-get plist req
)
1679 (defun auth-source--decode-octal-string (string)
1680 "Convert octal string to utf-8 string. E.g: 'a\134b' to 'a\b'"
1681 (let ((list (string-to-list string
))
1682 (size (length string
)))
1683 (decode-coding-string
1684 (apply #'unibyte-string
1685 (cl-loop for i
= 0 then
(+ i
(if (eq (nth i list
) ?
\\) 4 1))
1686 for var
= (nth i list
)
1689 collect
(string-to-number
1690 (concat (cl-subseq list
(+ i
1) (+ i
4))) 8)
1695 (cl-defun auth-source-macos-keychain-search-items (coll _type _max host port
1696 &key label type user
1698 (let* ((keychain-generic (eq type
'macos-keychain-generic
))
1699 (args `(,(if keychain-generic
1700 "find-generic-password"
1701 "find-internet-password")
1703 (ret (list :type type
)))
1705 (setq args
(append args
(list "-l" label
))))
1707 (setq args
(append args
(list (if keychain-generic
"-c" "-s") host
))))
1709 (setq args
(append args
(list "-a" user
))))
1712 (if keychain-generic
1713 (setq args
(append args
(list "-s" port
)))
1714 (setq args
(append args
(list
1715 (if (string-match "[0-9]+" port
) "-P" "-r")
1718 (unless (equal coll
"default")
1719 (setq args
(append args
(list coll
))))
1722 (apply #'call-process
"/usr/bin/security" nil t nil args
)
1723 (goto-char (point-min))
1726 ((looking-at "^password: \\(?:0x[0-9A-F]+\\)? *\"\\(.+\\)\"")
1727 (setq ret
(auth-source-macos-keychain-result-append
1731 (let ((v (auth-source--decode-octal-string
1734 ;; TODO: check if this is really the label
1735 ;; match 0x00000007 <blob>="AppleID"
1737 "^[ ]+0x00000007 <blob>=\\(?:0x[0-9A-F]+\\)? *\"\\(.+\\)\"")
1738 (setq ret
(auth-source-macos-keychain-result-append
1742 (auth-source--decode-octal-string (match-string 1)))))
1743 ;; match "crtr"<uint32>="aapl"
1744 ;; match "svce"<blob>="AppleID"
1746 "^[ ]+\"\\([a-z]+\\)\"[^=]+=\\(?:0x[0-9A-F]+\\)? *\"\\(.+\\)\"")
1747 (setq ret
(auth-source-macos-keychain-result-append
1750 (auth-source--decode-octal-string (match-string 1))
1751 (auth-source--decode-octal-string (match-string 2))))))
1753 ;; return `ret' iff it has the :secret key
1754 (and (plist-get ret
:secret
) (list ret
))))
1756 (defun auth-source-macos-keychain-result-append (result generic k v
)
1758 (push (auth-source--symbol-keyword
1760 ((equal k
"acct") "user")
1761 ;; for generic keychains, creator is host, service is port
1762 ((and generic
(equal k
"crtr")) "host")
1763 ((and generic
(equal k
"svce")) "port")
1764 ;; for internet keychains, protocol is port, server is host
1765 ((and (not generic
) (equal k
"ptcl")) "port")
1766 ((and (not generic
) (equal k
"srvr")) "host")
1770 (defun auth-source-macos-keychain-create (&rest spec
)
1774 ;;; Backend specific parsing: PLSTORE backend
1776 (cl-defun auth-source-plstore-search (&rest spec
1777 &key backend create delete max
1779 "Search the PLSTORE; spec is like `auth-source'."
1780 (let* ((store (oref backend data
))
1781 (max (or max
5000)) ; sanity check: default to stop at 5K
1782 (ignored-keys '(:create
:delete
:max
:backend
:label
:require
:type
))
1783 (search-keys (cl-loop for i below
(length spec
) by
2
1784 unless
(memq (nth i spec
) ignored-keys
)
1785 collect
(nth i spec
)))
1786 ;; build a search spec without the ignored keys
1787 ;; if a search key is nil or t (match anything), we skip it
1788 (search-spec (apply #'append
(mapcar
1790 (let ((v (plist-get spec k
)))
1798 ;; needed keys (always including host, login, port, and secret)
1799 (returned-keys (delete-dups (append
1800 '(:host
:login
:port
:secret
)
1802 (items (plstore-find store search-spec
))
1803 (item-names (mapcar #'car items
))
1804 (items (butlast items
(- (length items
) max
)))
1805 ;; convert the item to a full plist
1806 (items (mapcar (lambda (item)
1807 (let* ((plist (copy-tree (cdr item
)))
1808 (secret (plist-member plist
:secret
)))
1812 (let ((v (car (cdr secret
))))
1816 ;; ensure each item has each key in `returned-keys'
1817 (items (mapcar (lambda (plist)
1820 (mapcar (lambda (req)
1821 (if (plist-get plist req
)
1828 ;; if we need to create an entry AND none were found to match
1832 ;; create based on the spec and record the value
1834 ;; if the user did not want to create the entry
1835 ;; in the file, it will be returned
1836 (apply (slot-value backend
'create-function
) spec
)
1837 ;; if not, we do the search again without :create
1838 ;; to get the updated data.
1840 ;; the result will be returned, even if the search fails
1841 (apply #'auth-source-plstore-search
1842 (plist-put spec
:create nil
)))))
1845 (dolist (item-name item-names
)
1846 (plstore-delete store item-name
))
1847 (plstore-save store
)))
1850 (cl-defun auth-source-plstore-create (&rest spec
1851 &key backend host port create
1853 (let* ((base-required '(host user port secret
))
1854 (base-secret '(secret))
1855 ;; we know (because of an assertion in auth-source-search) that the
1856 ;; :create parameter is either t or a list (which includes nil)
1857 (create-extra (if (eq t create
) nil create
))
1858 (current-data (car (auth-source-search :max
1
1861 (required (append base-required create-extra
))
1862 ;; `valist' is an alist
1864 ;; `artificial' will be returned if no creation is needed
1868 ;; only for base required elements (defined as function parameters):
1869 ;; fill in the valist with whatever data we may have from the search
1870 ;; we complete the first value if it's a list and use the value otherwise
1871 (dolist (br base-required
)
1872 (let ((val (plist-get spec
(auth-source--symbol-keyword br
))))
1874 (let ((br-choice (cond
1875 ;; all-accepting choice (predicate is t)
1877 ;; just the value otherwise
1880 (auth-source--aput valist br br-choice
))))))
1882 ;; for extra required elements, see if the spec includes a value for them
1883 (dolist (er create-extra
)
1884 (let ((k (auth-source--symbol-keyword er
))
1885 (keys (cl-loop for i below
(length spec
) by
2
1886 collect
(nth i spec
))))
1888 (auth-source--aput valist er
(plist-get spec k
)))))
1890 ;; for each required element
1891 (dolist (r required
)
1892 (let* ((data (auth-source--aget valist r
))
1893 ;; take the first element if the data is a list
1894 (data (or (auth-source-netrc-element-or-first data
)
1895 (plist-get current-data
1896 (auth-source--symbol-keyword r
))))
1897 ;; this is the default to be offered
1898 (given-default (auth-source--aget
1899 auth-source-creation-defaults r
))
1900 ;; the default supplementals are simple:
1901 ;; for the user, try `given-default' and then (user-login-name);
1902 ;; otherwise take `given-default'
1904 ((and (not given-default
) (eq r
'user
))
1907 (printable-defaults (list
1910 (auth-source-netrc-element-or-first
1911 (auth-source--aget valist
'user
))
1912 (plist-get artificial
:user
)
1916 (auth-source-netrc-element-or-first
1917 (auth-source--aget valist
'host
))
1918 (plist-get artificial
:host
)
1922 (auth-source-netrc-element-or-first
1923 (auth-source--aget valist
'port
))
1924 (plist-get artificial
:port
)
1926 (prompt (or (auth-source--aget auth-source-creation-prompts r
)
1928 (secret "%p password for %u@%h: ")
1929 (user "%p user name for %h: ")
1930 (host "%p host name for user %u: ")
1931 (port "%p port for %u@%h: "))
1932 (format "Enter %s (%%u@%%h:%%p): " r
)))
1933 (prompt (auth-source-format-prompt
1935 `((?u
,(auth-source--aget printable-defaults
'user
))
1936 (?h
,(auth-source--aget printable-defaults
'host
))
1937 (?p
,(auth-source--aget printable-defaults
'port
))))))
1939 ;; Store the data, prompting for the password if needed.
1942 (or (eval default
) (read-passwd prompt
))
1943 (if (stringp default
)
1945 (if (string-match ": *\\'" prompt
)
1946 (concat (substring prompt
0 (match-beginning 0))
1947 " (default " default
"): ")
1948 (concat prompt
"(default " default
") "))
1953 (if (member r base-secret
)
1954 (setq secret-artificial
1955 (plist-put secret-artificial
1956 (auth-source--symbol-keyword r
)
1958 (setq artificial
(plist-put artificial
1959 (auth-source--symbol-keyword r
)
1961 (plstore-put (oref backend data
)
1962 (sha1 (format "%s@%s:%s"
1963 (plist-get artificial
:user
)
1964 (plist-get artificial
:host
)
1965 (plist-get artificial
:port
)))
1966 artificial secret-artificial
)
1967 (if (y-or-n-p (format "Save auth info to file %s? "
1968 (plstore-get-file (oref backend data
))))
1969 (plstore-save (oref backend data
)))))
1973 ;; (auth-source-user-or-password '("login" "password") "imap.myhost.com" t "tzz")
1975 ;; deprecate the old interface
1976 (make-obsolete 'auth-source-user-or-password
1977 'auth-source-search
"Emacs 24.1")
1978 (make-obsolete 'auth-source-forget-user-or-password
1979 'auth-source-forget
"Emacs 24.1")
1981 (defun auth-source-user-or-password
1982 (mode host port
&optional username create-missing delete-existing
)
1983 "Find MODE (string or list of strings) matching HOST and PORT.
1985 DEPRECATED in favor of `auth-source-search'!
1987 USERNAME is optional and will be used as \"login\" in a search
1988 across the Secret Service API (see secrets.el) if the resulting
1989 items don't have a username. This means that if you search for
1990 username \"joe\" and it matches an item but the item doesn't have
1991 a :user attribute, the username \"joe\" will be returned.
1993 A non nil DELETE-EXISTING means deleting any matching password
1994 entry in the respective sources. This is useful only when
1995 CREATE-MISSING is non nil as well; the intended use case is to
1996 remove wrong password entries.
1998 If no matching entry is found, and CREATE-MISSING is non nil,
1999 the password will be retrieved interactively, and it will be
2000 stored in the password database which matches best (see
2003 MODE can be \"login\" or \"password\"."
2004 (auth-source-do-debug
2005 "auth-source-user-or-password: DEPRECATED get %s for %s (%s) + user=%s"
2006 mode host port username
)
2008 (let* ((listy (listp mode
))
2009 (mode (if listy mode
(list mode
)))
2010 ;; (cname (if username
2011 ;; (format "%s %s:%s %s" mode host port username)
2012 ;; (format "%s %s:%s" mode host port)))
2013 (search (list :host host
:port port
))
2014 (search (if username
(append search
(list :user username
)) search
))
2015 (search (if create-missing
2016 (append search
(list :create t
))
2018 (search (if delete-existing
2019 (append search
(list :delete t
))
2021 ;; (found (if (not delete-existing)
2022 ;; (gethash cname auth-source-cache)
2023 ;; (remhash cname auth-source-cache)
2028 (auth-source-do-debug
2029 "auth-source-user-or-password: DEPRECATED cached %s=%s for %s (%s) + %s"
2031 ;; don't show the password
2032 (if (and (member "password" mode
) t
)
2036 found
) ; return the found data
2037 ;; else, if not found, search with a max of 1
2038 (let ((choice (nth 0 (apply #'auth-source-search
2039 (append '(:max
1) search
)))))
2043 ((equal "password" m
)
2044 (push (if (plist-get choice
:secret
)
2045 (funcall (plist-get choice
:secret
))
2048 (push (plist-get choice
:user
) found
)))))
2049 (setq found
(nreverse found
))
2050 (setq found
(if listy found
(car-safe found
)))))
2054 (defun auth-source-user-and-password (host &optional user
)
2055 (let* ((auth-info (car
2061 :require
'(:user
:secret
)
2066 :require
'(:user
:secret
)
2068 (user (plist-get auth-info
:user
))
2069 (password (plist-get auth-info
:secret
)))
2070 (when (functionp password
)
2071 (setq password
(funcall password
)))
2072 (list user password auth-info
)))
2074 (provide 'auth-source
)
2076 ;;; auth-source.el ends here