1 ;;; auth-source.el --- authentication sources for Gnus and Emacs -*- lexical-binding: t -*-
3 ;; Copyright (C) 2008-2017 Free Software Foundation, Inc.
5 ;; Author: Ted Zlatanov <tzz@lifelogs.com>
8 ;; This file is part of GNU Emacs.
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
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 (defvar auth-source-magic
"auth-source-magic ")
205 (defcustom auth-source-do-cache t
206 "Whether auth-source should cache information with `password-cache'."
208 :version
"23.2" ;; No Gnus
211 (defcustom auth-source-debug nil
212 "Whether auth-source should log debug messages.
214 If the value is nil, debug messages are not logged.
216 If the value is t, debug messages are logged with `message'. In
217 that case, your authentication data will be in the clear (except
220 If the value is a function, debug messages are logged by calling
221 that function using the same arguments as `message'."
223 :version
"23.2" ;; No Gnus
225 :tag
"auth-source debugging mode"
226 (const :tag
"Log using `message' to the *Messages* buffer" t
)
227 (const :tag
"Log all trivia with `message' to the *Messages* buffer"
229 (function :tag
"Function that takes arguments like `message'")
230 (const :tag
"Don't log anything" nil
)))
232 (defcustom auth-sources
'("~/.authinfo" "~/.authinfo.gpg" "~/.netrc")
233 "List of authentication sources.
234 Each entry is the authentication type with optional properties.
235 Entries are tried in the order in which they appear.
236 See Info node `(auth)Help for users' for details.
238 If an entry names a file with the \".gpg\" extension and you have
239 EPA/EPG set up, the file will be encrypted and decrypted
240 automatically. See Info node `(epa)Encrypting/decrypting gpg files'
243 It's best to customize this with `\\[customize-variable]' because the choices
244 can get pretty complex."
246 :version
"24.1" ;; No Gnus
247 :type
`(repeat :tag
"Authentication Sources"
249 (string :tag
"Just a file")
250 (const :tag
"Default Secrets API Collection" default
)
251 (const :tag
"Login Secrets API Collection" "secrets:Login")
252 (const :tag
"Temp Secrets API Collection" "secrets:session")
254 (const :tag
"Default internet Mac OS Keychain"
255 macos-keychain-internet
)
257 (const :tag
"Default generic Mac OS Keychain"
258 macos-keychain-generic
)
260 (list :tag
"Source definition"
261 (const :format
"" :value
:source
)
262 (choice :tag
"Authentication backend choice"
263 (string :tag
"Authentication Source (file)")
265 :tag
"Secret Service API/KWallet/GNOME Keyring"
266 (const :format
"" :value
:secrets
)
267 (choice :tag
"Collection to use"
268 (string :tag
"Collection name")
269 (const :tag
"Default" default
)
270 (const :tag
"Login" "Login")
272 :tag
"Temporary" "session")))
274 :tag
"Mac OS internet Keychain"
276 :value
:macos-keychain-internet
)
277 (choice :tag
"Collection to use"
278 (string :tag
"internet Keychain path")
279 (const :tag
"default" default
)))
281 :tag
"Mac OS generic Keychain"
283 :value
:macos-keychain-generic
)
284 (choice :tag
"Collection to use"
285 (string :tag
"generic Keychain path")
286 (const :tag
"default" default
))))
287 (repeat :tag
"Extra Parameters" :inline t
288 (choice :tag
"Extra parameter"
291 (const :format
"" :value
:host
)
292 (choice :tag
"Host (machine) choice"
295 :tag
"Regular expression")))
298 (const :format
"" :value
:port
)
302 ,@auth-source-protocols-customize
))
303 (list :tag
"User" :inline t
304 (const :format
"" :value
:user
)
306 :tag
"Personality/Username"
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."
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
)
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
)
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)."
344 (let* ((prompt-choices
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
)))
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'."
367 (cl-dolist (f auth-source-backend-parser-functions
)
368 (when (setq backend
(funcall f entry
))
372 ;; none of the parsers worked
374 "auth-source-backend-parse: invalid backend spec: %S" entry
)
375 (setq backend
(make-instance 'auth-source-backend
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
`(:source
,entry
)))
386 ;; a file name with parameters
387 ((stringp (plist-get entry
:source
))
388 (if (equal (file-name-extension (plist-get entry
:source
)) "plist")
390 (plist-get entry
:source
)
391 :source
(plist-get entry
:source
)
393 :search-function
#'auth-source-plstore-search
394 :create-function
#'auth-source-plstore-create
395 :data
(plstore-open (plist-get entry
:source
)))
397 (plist-get entry
:source
)
398 :source
(plist-get entry
:source
)
400 :search-function
#'auth-source-netrc-search
401 :create-function
#'auth-source-netrc-create
)))))
403 ;; Note this function should be last in the parser functions, so we add it first
404 (add-hook 'auth-source-backend-parser-functions
'auth-source-backends-parser-file
)
406 (defun auth-source-backends-parser-macos-keychain (entry)
407 ;; take macos-keychain-{internet,generic}:XYZ and use it as macOS
408 ;; Keychain "XYZ" matching any user, host, and protocol
409 (when (and (stringp entry
) (string-match "^macos-keychain-internet:\\(.+\\)"
411 (setq entry
`(:source
(:macos-keychain-internet
412 ,(match-string 1 entry
)))))
413 (when (and (stringp entry
) (string-match "^macos-keychain-generic:\\(.+\\)"
415 (setq entry
`(:source
(:macos-keychain-generic
416 ,(match-string 1 entry
)))))
417 ;; take 'macos-keychain-internet or generic and use it as a Mac OS
418 ;; Keychain collection matching any user, host, and protocol
419 (when (eq entry
'macos-keychain-internet
)
420 (setq entry
'(:source
(:macos-keychain-internet default
))))
421 (when (eq entry
'macos-keychain-generic
)
422 (setq entry
'(:source
(:macos-keychain-generic default
))))
424 ;; the macOS Keychain
426 (not (null (plist-get entry
:source
))) ; the source must not be nil
427 (listp (plist-get entry
:source
)) ; and it must be a list
429 (plist-get (plist-get entry
:source
) :macos-keychain-generic
)
430 (plist-get (plist-get entry
:source
) :macos-keychain-internet
)))
432 (let* ((source-spec (plist-get entry
:source
))
433 (keychain-generic (plist-get source-spec
:macos-keychain-generic
))
434 (keychain-type (if keychain-generic
435 'macos-keychain-generic
436 'macos-keychain-internet
))
437 (source (plist-get source-spec
(if keychain-generic
438 :macos-keychain-generic
439 :macos-keychain-internet
))))
441 (when (symbolp source
)
442 (setq source
(symbol-name source
)))
445 (format "Mac OS Keychain (%s)" source
)
448 :search-function
#'auth-source-macos-keychain-search
449 :create-function
#'auth-source-macos-keychain-create
)))))
451 (add-hook 'auth-source-backend-parser-functions
'auth-source-backends-parser-macos-keychain
)
453 (defun auth-source-backends-parser-secrets (entry)
454 ;; take secrets:XYZ and use it as Secrets API collection "XYZ"
455 ;; matching any user, host, and protocol
456 (when (and (stringp entry
) (string-match "^secrets:\\(.+\\)" entry
))
457 (setq entry
`(:source
(:secrets
,(match-string 1 entry
)))))
458 ;; take 'default and use it as a Secrets API default collection
459 ;; matching any user, host, and protocol
460 (when (eq entry
'default
)
461 (setq entry
'(:source
(:secrets default
))))
463 ;; the Secrets API. We require the package, in order to have a
464 ;; defined value for `secrets-enabled'.
466 (not (null (plist-get entry
:source
))) ; the source must not be nil
467 (listp (plist-get entry
:source
)) ; and it must be a list
468 (not (null (plist-get
469 (plist-get entry
:source
)
470 :secrets
))) ; the source must have :secrets
471 (require 'secrets nil t
) ; and we must load the Secrets API
472 secrets-enabled
) ; and that API must be enabled
474 ;; the source is either the :secrets key in ENTRY or
475 ;; if that's missing or nil, it's "session"
476 (let ((source (plist-get (plist-get entry
:source
) :secrets
)))
478 ;; if the source is a symbol, we look for the alias named so,
479 ;; and if that alias is missing, we use "Login"
480 (when (symbolp source
)
481 (setq source
(or (secrets-get-alias (symbol-name source
))
484 (if (featurep 'secrets
)
486 (format "Secrets API (%s)" source
)
489 :search-function
#'auth-source-secrets-search
490 :create-function
#'auth-source-secrets-create
)
492 "auth-source-backend-parse: no Secrets API, ignoring spec: %S" entry
)
494 (format "Ignored Secrets API (%s)" source
)
498 (add-hook 'auth-source-backend-parser-functions
'auth-source-backends-parser-secrets
)
500 (defun auth-source-backend-parse-parameters (entry backend
)
501 "Fills in the extra auth-source-backend parameters of ENTRY.
502 Using the plist ENTRY, get the :host, :port, and :user search
504 (let ((entry (if (stringp entry
)
508 (when (setq val
(plist-get entry
:host
))
509 (oset backend host val
))
510 (when (setq val
(plist-get entry
:user
))
511 (oset backend user val
))
512 (when (setq val
(plist-get entry
:port
))
513 (oset backend port val
)))
516 ;; (mapcar 'auth-source-backend-parse auth-sources)
518 (cl-defun auth-source-search (&rest spec
519 &key max require create delete
521 "Search or modify authentication backends according to SPEC.
523 This function parses `auth-sources' for matches of the SPEC
524 plist. It can optionally create or update an authentication
525 token if requested. A token is just a standard Emacs property
526 list with a :secret property that can be a function; all the
527 other properties will always hold scalar values.
529 Typically the :secret property, if present, contains a password.
531 Common search keys are :max, :host, :port, and :user. In
532 addition, :create specifies if and how tokens will be created.
533 Finally, :type can specify which backend types you want to check.
535 A string value is always matched literally. A symbol is matched
536 as its string value, literally. All the SPEC values can be
537 single values (symbol or string) or lists thereof (in which case
538 any of the search terms matches).
540 :create t means to create a token if possible.
542 A new token will be created if no matching tokens were found.
543 The new token will have only the keys the backend requires. For
544 the netrc backend, for instance, that's the user, host, and
549 \(let ((auth-source-creation-defaults \\='((user . \"defaultUser\")
550 (A . \"default A\"))))
551 (auth-source-search :host \"mine\" :type \\='netrc :max 1
552 :P \"pppp\" :Q \"qqqq\"
557 \"Search for any entry matching host `mine' in backends of type
558 `netrc', maximum one result.
560 Create a new entry if you found none. The netrc backend will
561 automatically require host, user, and port. The host will be
562 `mine'. We prompt for the user with default `defaultUser' and
563 for the port without a default. We will not prompt for A, Q,
564 or P. The resulting token will only have keys user, host, and
567 :create \\='(A B C) also means to create a token if possible.
569 The behavior is like :create t but if the list contains any
570 parameter, that parameter will be required in the resulting
571 token. The value for that parameter will be obtained from the
572 search parameters or from user input. If any queries are needed,
573 the alist `auth-source-creation-defaults' will be checked for the
574 default value. If the user, host, or port are missing, the alist
575 `auth-source-creation-prompts' will be used to look up the
576 prompts IN THAT ORDER (so the `user' prompt will be queried first,
577 then `host', then `port', and finally `secret'). Each prompt string
578 can use %u, %h, and %p to show the user, host, and port.
582 \(let ((auth-source-creation-defaults \\='((user . \"defaultUser\")
583 (A . \"default A\")))
584 (auth-source-creation-prompts
585 \\='((password . \"Enter IMAP password for %h:%p: \"))))
586 (auth-source-search :host \\='(\"nonesuch\" \"twosuch\") :type \\='netrc :max 1
587 :P \"pppp\" :Q \"qqqq\"
588 :create \\='(A B Q)))
592 \"Search for any entry matching host `nonesuch'
593 or `twosuch' in backends of type `netrc', maximum one result.
595 Create a new entry if you found none. The netrc backend will
596 automatically require host, user, and port. The host will be
597 `nonesuch' and Q will be `qqqq'. We prompt for the password
598 with the shown prompt. We will not prompt for Q. The resulting
599 token will have keys user, host, port, A, B, and Q. It will not
600 have P with any value, even though P is used in the search to
601 find only entries that have P set to `pppp'.\"
603 When multiple values are specified in the search parameter, the
604 user is prompted for which one. So :host (X Y Z) would ask the
605 user to choose between X, Y, and Z.
607 This creation can fail if the search was not specific enough to
608 create a new token (it's up to the backend to decide that). You
609 should `catch' the backend-specific error as usual. Some
610 backends (netrc, at least) will prompt the user rather than throw
613 :require (A B C) means that only results that contain those
614 tokens will be returned. Thus for instance requiring :secret
615 will ensure that any results will actually have a :secret
618 :delete t means to delete any found entries. nil by default.
619 Use `auth-source-delete' in ELisp code instead of calling
620 `auth-source-search' directly with this parameter.
622 :type (X Y Z) will check only those backend types. `netrc' and
623 `secrets' are the only ones supported right now.
625 :max N means to try to return at most N items (defaults to 1).
626 More than N items may be returned, depending on the search and
629 When :max is 0 the function will return just t or nil to indicate
630 if any matches were found.
632 :host (X Y Z) means to match only hosts X, Y, or Z according to
633 the match rules above. Defaults to t.
635 :user (X Y Z) means to match only users X, Y, or Z according to
636 the match rules above. Defaults to t.
638 :port (P Q R) means to match only protocols P, Q, or R.
641 :K (V1 V2 V3) for any other key K will match values V1, V2, or
642 V3 (note the match rules above).
644 The return value is a list with at most :max tokens. Each token
645 is a plist with keys :backend :host :port :user, plus any other
646 keys provided by the backend (notably :secret). But note the
647 exception for :max 0, which see above.
649 The token can hold a :save-function key. If you call that, the
650 user will be prompted to save the data to the backend. You can't
651 request that this should happen right after creation, because
652 `auth-source-search' has no way of knowing if the token is
653 actually useful. So the caller must arrange to call this function.
655 The token's :secret key can hold a function. In that case you
656 must call it to obtain the actual value."
657 (let* ((backends (mapcar #'auth-source-backend-parse auth-sources
))
659 (ignored-keys '(:require
:create
:delete
:max
))
660 (keys (cl-loop for i below
(length spec
) by
2
661 unless
(memq (nth i spec
) ignored-keys
)
662 collect
(nth i spec
)))
663 (cached (auth-source-remembered-p spec
))
664 ;; note that we may have cached results but found is still nil
665 ;; (there were no results from the search)
666 (found (auth-source-recall spec
))
669 (if (and cached auth-source-do-cache
)
670 (auth-source-do-debug
671 "auth-source-search: found %d CACHED results matching %S"
675 (or (eq t create
) (listp create
)) t
676 "Invalid auth-source :create parameter (must be t or a list): %s %s")
680 "Invalid auth-source :require parameter (must be a list): %s")
682 (setq filtered-backends
(copy-sequence backends
))
683 (dolist (backend backends
)
684 (cl-dolist (key keys
)
685 ;; ignore invalid slots
687 (unless (auth-source-search-collection
689 (slot-value backend key
))
690 (setq filtered-backends
(delq backend filtered-backends
))
692 (invalid-slot-name nil
))))
694 (auth-source-do-trivia
695 "auth-source-search: found %d backends matching %S"
696 (length filtered-backends
) spec
)
698 ;; (debug spec "filtered" filtered-backends)
699 ;; First go through all the backends without :create, so we can
701 (setq found
(auth-source-search-backends filtered-backends
705 ;; create is always nil here
709 (auth-source-do-debug
710 "auth-source-search: found %d results (max %d) matching %S"
711 (length found
) max spec
)
713 ;; If we didn't find anything, then we allow the backend(s) to
714 ;; create the entries.
717 (setq found
(auth-source-search-backends filtered-backends
723 (auth-source-do-debug
724 "auth-source-search: CREATED %d results (max %d) matching %S"
725 (length found
) max spec
))
727 ;; note we remember the lack of result too, if it's applicable
728 (when auth-source-do-cache
729 (auth-source-remember spec found
)))
735 (defun auth-source-search-backends (backends spec max create delete require
)
736 (let ((max (if (zerop max
) 1 max
)) ; stop with 1 match if we're asked for zero
738 (dolist (backend backends
)
739 (when (> max
(length matches
)) ; if we need more matches...
740 (let* ((bmatches (apply
741 (slot-value backend
'search-function
)
743 :type
(slot-value backend
'type
)
744 ;; note we're overriding whatever the spec
745 ;; has for :max, :require, :create, and :delete
752 (auth-source-do-trivia
753 "auth-source-search-backend: got %d (max %d) in %s:%s matching %S"
754 (length bmatches
) max
755 (slot-value backend
'type
)
756 (slot-value backend
'source
)
758 (setq matches
(append matches bmatches
))))))
761 (defun auth-source-delete (&rest spec
)
762 "Delete entries from the authentication backends according to SPEC.
763 Calls `auth-source-search' with the :delete property in SPEC set to t.
764 The backend may not actually delete the entries.
766 Returns the deleted entries."
767 (auth-source-search (plist-put spec
:delete t
)))
769 (defun auth-source-search-collection (collection value
)
770 "Returns t is VALUE is t or COLLECTION is t or COLLECTION contains VALUE."
771 (when (and (atom collection
) (not (eq t collection
)))
772 (setq collection
(list collection
)))
774 ;; (debug :collection collection :value value)
775 (or (eq collection t
)
777 (equal collection value
)
778 (member value collection
)))
780 (defvar auth-source-netrc-cache nil
)
782 (defun auth-source-forget-all-cached ()
783 "Forget all cached auth-source data."
785 (cl-do-symbols (sym password-data
)
786 ;; when the symbol name starts with auth-source-magic
787 (when (string-match (concat "^" auth-source-magic
) (symbol-name sym
))
789 (password-cache-remove (symbol-name sym
))))
790 (setq auth-source-netrc-cache nil
))
792 (defun auth-source-format-cache-entry (spec)
793 "Format SPEC entry to put it in the password cache."
794 (concat auth-source-magic
(format "%S" spec
)))
796 (defun auth-source-remember (spec found
)
797 "Remember FOUND search results for SPEC."
798 (let ((password-cache-expiry auth-source-cache-expiry
))
800 (auth-source-format-cache-entry spec
) found
)))
802 (defun auth-source-recall (spec)
803 "Recall FOUND search results for SPEC."
804 (password-read-from-cache (auth-source-format-cache-entry spec
)))
806 (defun auth-source-remembered-p (spec)
807 "Check if SPEC is remembered."
809 (auth-source-format-cache-entry spec
)))
811 (defun auth-source-forget (spec)
812 "Forget any cached data matching SPEC exactly.
814 This is the same SPEC you passed to `auth-source-search'.
815 Returns t or nil for forgotten or not found."
816 (password-cache-remove (auth-source-format-cache-entry spec
)))
818 (defun auth-source-forget+ (&rest spec
)
819 "Forget any cached data matching SPEC. Returns forgotten count.
821 This is not a full `auth-source-search' spec but works similarly.
822 For instance, \(:host \"myhost\" \"yourhost\") would find all the
823 cached data that was found with a search for those two hosts,
824 while \(:host t) would find all host entries."
827 (cl-do-symbols (sym password-data
)
828 ;; when the symbol name matches with auth-source-magic
829 (when (and (setq sname
(symbol-name sym
))
830 (string-match (concat "^" auth-source-magic
"\\(.+\\)")
832 ;; and the spec matches what was stored in the cache
833 (auth-source-specmatchp spec
(read (match-string 1 sname
))))
835 (password-cache-remove sname
)
839 (defun auth-source-specmatchp (spec stored
)
840 (let ((keys (cl-loop for i below
(length spec
) by
2
841 collect
(nth i spec
))))
843 (cl-dolist (key keys
)
844 (unless (auth-source-search-collection (plist-get stored key
)
845 (plist-get spec key
))
849 (defun auth-source-pick-first-password (&rest spec
)
850 "Pick the first secret found from applying SPEC to `auth-source-search'."
851 (let* ((result (nth 0 (apply #'auth-source-search
(plist-put spec
:max
1))))
852 (secret (plist-get result
:secret
)))
854 (if (functionp secret
)
858 (defun auth-source-format-prompt (prompt alist
)
859 "Format PROMPT using %x (for any character x) specifiers in ALIST."
861 (let ((c (nth 0 cell
))
864 (setq prompt
(replace-regexp-in-string (format "%%%c" c
)
869 (defun auth-source-ensure-strings (values)
872 (unless (listp values
)
873 (setq values
(list values
)))
874 (mapcar (lambda (value)
880 ;;; Backend specific parsing: netrc/authinfo backend
882 (defun auth-source--aput-1 (alist key val
)
885 (while (and (consp rest
) (not (equal key
(caar rest
))))
886 (push (pop rest
) seen
))
888 (if (null rest
) alist
889 (nconc (nreverse seen
)
890 (if (equal key
(caar rest
)) (cdr rest
) rest
))))))
891 (defmacro auth-source--aput
(var key val
)
892 `(setq ,var
(auth-source--aput-1 ,var
,key
,val
)))
894 (defun auth-source--aget (alist key
)
895 (cdr (assoc key alist
)))
897 ;; (auth-source-netrc-parse :file "~/.authinfo.gpg")
898 (cl-defun auth-source-netrc-parse (&key file max host user port require
900 "Parse FILE and return a list of all entries in the file.
901 Note that the MAX parameter is used so we can exit the parse early."
903 ;; We got already parsed contents; just return it.
905 (when (file-exists-p file
)
906 (setq port
(auth-source-ensure-strings port
))
908 (let* ((max (or max
5000)) ; sanity check: default to stop at 5K
910 (cached (cdr-safe (assoc file auth-source-netrc-cache
)))
911 (cached-mtime (plist-get cached
:mtime
))
912 (cached-secrets (plist-get cached
:secret
))
913 (check (lambda(alist)
915 (auth-source-search-collection
918 (auth-source--aget alist
"machine")
919 (auth-source--aget alist
"host")
921 (auth-source-search-collection
924 (auth-source--aget alist
"login")
925 (auth-source--aget alist
"account")
926 (auth-source--aget alist
"user")
928 (auth-source-search-collection
931 (auth-source--aget alist
"port")
932 (auth-source--aget alist
"protocol")
935 ;; the required list of keys is nil, or
937 ;; every element of require is in n(ormalized)
938 (let ((n (nth 0 (auth-source-netrc-normalize
939 (list alist
) file
))))
940 (cl-loop for req in require
941 always
(plist-get n req
)))))))
944 (if (and (functionp cached-secrets
)
946 (nth 5 (file-attributes file
))))
948 (auth-source-do-trivia
949 "auth-source-netrc-parse: using CACHED file data for %s"
951 (insert (funcall cached-secrets
)))
952 (insert-file-contents file
)
953 ;; cache all netrc files (used to be just .gpg files)
954 ;; Store the contents of the file heavily encrypted in memory.
955 ;; (note for the irony-impaired: they are just obfuscated)
957 auth-source-netrc-cache file
958 (list :mtime
(nth 5 (file-attributes file
))
959 :secret
(let ((v (mapcar #'1+ (buffer-string))))
960 (lambda () (apply #'string
(mapcar #'1- v
)))))))
961 (goto-char (point-min))
962 (let ((entries (auth-source-netrc-parse-entries check max
))
964 (while (setq alist
(pop entries
))
965 (push (nreverse alist
) result
)))
968 (when auth-source-gpg-encrypt-to
969 ;; (see bug#7487) making `epa-file-encrypt-to' local to
970 ;; this buffer lets epa-file skip the key selection query
971 ;; (see the `local-variable-p' check in
972 ;; `epa-file-write-region').
973 (unless (local-variable-p 'epa-file-encrypt-to
(current-buffer))
974 (make-local-variable 'epa-file-encrypt-to
))
975 (if (listp auth-source-gpg-encrypt-to
)
976 (setq epa-file-encrypt-to auth-source-gpg-encrypt-to
)))
978 ;; ask AFTER we've successfully opened the file
979 (when (y-or-n-p (format "Save file %s? (%d deletions)"
981 (write-region (point-min) (point-max) file nil
'silent
)
982 (auth-source-do-debug
983 "auth-source-netrc-parse: modified %d lines in %s"
986 (nreverse result
))))))
988 (defun auth-source-netrc-parse-next-interesting ()
989 "Advance to the next interesting position in the current buffer."
990 ;; If we're looking at a comment or are at the end of the line, move forward
991 (while (or (looking-at "#")
995 (skip-chars-forward "\t "))
997 (defun auth-source-netrc-parse-one ()
998 "Read one thing from the current buffer."
999 (auth-source-netrc-parse-next-interesting)
1001 (when (or (looking-at "'\\([^']*\\)'")
1002 (looking-at "\"\\([^\"]*\\)\"")
1003 (looking-at "\\([^ \t\n]+\\)"))
1004 (forward-char (length (match-string 0)))
1005 (auth-source-netrc-parse-next-interesting)
1006 (match-string-no-properties 1)))
1008 ;; with thanks to org-mode
1009 (defsubst auth-source-current-line
(&optional pos
)
1011 (and pos
(goto-char pos
))
1012 ;; works also in narrowed buffer, because we start at 1, not point-min
1013 (+ (if (bolp) 1 0) (count-lines 1 (point)))))
1015 (defun auth-source-netrc-parse-entries(check max
)
1016 "Parse up to MAX netrc entries, passed by CHECK, from the current buffer."
1017 (let ((adder (lambda(check alist all
)
1020 (> max
(length all
))
1021 (funcall check alist
))
1024 item item2 all alist default
)
1025 (while (setq item
(auth-source-netrc-parse-one))
1026 (setq default
(equal item
"default"))
1027 ;; We're starting a new machine. Save the old one.
1030 (equal item
"machine")))
1031 ;; (auth-source-do-trivia
1032 ;; "auth-source-netrc-parse-entries: got entry %S" alist)
1033 (setq all
(funcall adder check alist all
)
1035 ;; In default entries, we don't have a next token.
1036 ;; We store them as ("machine" . t)
1038 (push (cons "machine" t
) alist
)
1039 ;; Not a default entry. Grab the next item.
1040 (when (setq item2
(auth-source-netrc-parse-one))
1041 ;; Did we get a "machine" value?
1042 (if (equal item2
"machine")
1044 "%s: Unexpected `machine' token at line %d"
1045 "auth-source-netrc-parse-entries"
1046 (auth-source-current-line))
1047 (push (cons item item2
) alist
)))))
1049 ;; Clean up: if there's an entry left over, use it.
1051 (setq all
(funcall adder check alist all
))
1052 ;; (auth-source-do-trivia
1053 ;; "auth-source-netrc-parse-entries: got2 entry %S" alist)
1057 (defvar auth-source-passphrase-alist nil
)
1059 (defun auth-source-token-passphrase-callback-function (_context _key-id file
)
1060 (let* ((file (file-truename file
))
1061 (entry (assoc file auth-source-passphrase-alist
))
1063 ;; return the saved passphrase, calling a function if needed
1064 (or (copy-sequence (if (functionp (cdr entry
))
1065 (funcall (cdr entry
))
1069 (setq entry
(list file
))
1070 (push entry auth-source-passphrase-alist
))
1073 (format "Passphrase for %s tokens: " file
)
1075 (setcdr entry
(let ((p (copy-sequence passphrase
)))
1079 (defun auth-source-epa-extract-gpg-token (secret file
)
1080 "Pass either the decoded SECRET or the gpg:BASE64DATA version.
1081 FILE is the file from which we obtained this token."
1082 (when (string-match "^gpg:\\(.+\\)" secret
)
1083 (setq secret
(base64-decode-string (match-string 1 secret
))))
1084 (let ((context (epg-make-context 'OpenPGP
)))
1085 (epg-context-set-passphrase-callback
1087 (cons #'auth-source-token-passphrase-callback-function
1089 (epg-decrypt-string context secret
)))
1091 (defvar pp-escape-newlines
)
1093 (defun auth-source-epa-make-gpg-token (secret file
)
1094 (let ((context (epg-make-context 'OpenPGP
))
1095 (pp-escape-newlines nil
)
1097 (setf (epg-context-armor context
) t
)
1098 (epg-context-set-passphrase-callback
1100 (cons #'auth-source-token-passphrase-callback-function
1102 (setq cipher
(epg-encrypt-string context secret nil
))
1105 (base64-encode-region (point-min) (point-max) t
)
1106 (concat "gpg:" (buffer-substring-no-properties
1110 (defun auth-source--symbol-keyword (symbol)
1111 (intern (format ":%s" symbol
)))
1113 (defun auth-source-netrc-normalize (alist filename
)
1114 (mapcar (lambda (entry)
1116 (while (setq item
(pop entry
))
1117 (let ((k (car item
))
1120 ;; apply key aliases
1121 (setq k
(cond ((member k
'("machine")) "host")
1122 ((member k
'("login" "account")) "user")
1123 ((member k
'("protocol")) "port")
1124 ((member k
'("password")) "secret")
1127 ;; send back the secret in a function (lexical binding)
1128 (when (equal k
"secret")
1129 (setq v
(let ((lexv v
)
1130 (token-decoder nil
))
1131 (when (string-match "^gpg:" lexv
)
1132 ;; it's a GPG token: create a token decoder
1133 ;; which unsets itself once
1137 (auth-source-epa-extract-gpg-token
1140 (setq token-decoder nil
)))))
1143 (setq lexv
(funcall token-decoder lexv
)))
1145 (setq ret
(plist-put ret
1146 (auth-source--symbol-keyword k
)
1151 (cl-defun auth-source-netrc-search (&rest spec
1152 &key backend require create
1153 type max host user port
1155 "Given a property list SPEC, return search matches from the :backend.
1156 See `auth-source-search' for details on SPEC."
1157 ;; just in case, check that the type is correct (null or same as the backend)
1158 (cl-assert (or (null type
) (eq type
(oref backend type
)))
1159 t
"Invalid netrc search: %s %s")
1161 (let ((results (auth-source-netrc-normalize
1162 (auth-source-netrc-parse
1165 :file
(oref backend source
)
1169 (oref backend source
))))
1171 ;; if we need to create an entry AND none were found to match
1175 ;; create based on the spec and record the value
1177 ;; if the user did not want to create the entry
1178 ;; in the file, it will be returned
1179 (apply (slot-value backend
'create-function
) spec
)
1180 ;; if not, we do the search again without :create
1181 ;; to get the updated data.
1183 ;; the result will be returned, even if the search fails
1184 (apply #'auth-source-netrc-search
1185 (plist-put spec
:create nil
)))))
1188 (defun auth-source-netrc-element-or-first (v)
1193 ;; (auth-source-search :host "nonesuch" :type 'netrc :max 1 :create t)
1194 ;; (auth-source-search :host "nonesuch" :type 'netrc :max 1 :create t :create-extra-keys '((A "default A") (B)))
1196 (cl-defun auth-source-netrc-create (&rest spec
1197 &key backend host port create
1199 (let* ((base-required '(host user port secret
))
1200 ;; we know (because of an assertion in auth-source-search) that the
1201 ;; :create parameter is either t or a list (which includes nil)
1202 (create-extra (if (eq t create
) nil create
))
1203 (current-data (car (auth-source-search :max
1
1206 (required (append base-required create-extra
))
1207 (file (oref backend source
))
1209 ;; `valist' is an alist
1211 ;; `artificial' will be returned if no creation is needed
1214 ;; only for base required elements (defined as function parameters):
1215 ;; fill in the valist with whatever data we may have from the search
1216 ;; we complete the first value if it's a list and use the value otherwise
1217 (dolist (br base-required
)
1218 (let ((val (plist-get spec
(auth-source--symbol-keyword br
))))
1220 (let ((br-choice (cond
1221 ;; all-accepting choice (predicate is t)
1223 ;; just the value otherwise
1226 (auth-source--aput valist br br-choice
))))))
1228 ;; for extra required elements, see if the spec includes a value for them
1229 (dolist (er create-extra
)
1230 (let ((k (auth-source--symbol-keyword er
))
1231 (keys (cl-loop for i below
(length spec
) by
2
1232 collect
(nth i spec
))))
1234 (auth-source--aput valist er
(plist-get spec k
)))))
1236 ;; for each required element
1237 (dolist (r required
)
1238 (let* ((data (auth-source--aget valist r
))
1239 ;; take the first element if the data is a list
1240 (data (or (auth-source-netrc-element-or-first data
)
1241 (plist-get current-data
1242 (auth-source--symbol-keyword r
))))
1243 ;; this is the default to be offered
1244 (given-default (auth-source--aget
1245 auth-source-creation-defaults r
))
1246 ;; the default supplementals are simple:
1247 ;; for the user, try `given-default' and then (user-login-name);
1248 ;; otherwise take `given-default'
1250 ((and (not given-default
) (eq r
'user
))
1253 (printable-defaults (list
1256 (auth-source-netrc-element-or-first
1257 (auth-source--aget valist
'user
))
1258 (plist-get artificial
:user
)
1262 (auth-source-netrc-element-or-first
1263 (auth-source--aget valist
'host
))
1264 (plist-get artificial
:host
)
1268 (auth-source-netrc-element-or-first
1269 (auth-source--aget valist
'port
))
1270 (plist-get artificial
:port
)
1272 (prompt (or (auth-source--aget auth-source-creation-prompts r
)
1274 (secret "%p password for %u@%h: ")
1275 (user "%p user name for %h: ")
1276 (host "%p host name for user %u: ")
1277 (port "%p port for %u@%h: "))
1278 (format "Enter %s (%%u@%%h:%%p): " r
)))
1279 (prompt (auth-source-format-prompt
1281 `((?u
,(auth-source--aget printable-defaults
'user
))
1282 (?h
,(auth-source--aget printable-defaults
'host
))
1283 (?p
,(auth-source--aget printable-defaults
'port
))))))
1285 ;; Store the data, prompting for the password if needed.
1288 ;; Special case prompt for passwords.
1289 ;; 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)))
1290 ;; TODO: or maybe leave as (setq auth-source-netrc-use-gpg-tokens 'never)
1291 (let* ((ep (format "Use GPG password tokens in %s?" file
))
1294 ((eq auth-source-netrc-use-gpg-tokens
'never
)
1296 ((listp auth-source-netrc-use-gpg-tokens
)
1297 (let ((check (copy-sequence
1298 auth-source-netrc-use-gpg-tokens
))
1301 (setq item
(pop check
))
1302 (when (or (eq (car item
) t
)
1303 (string-match (car item
) file
))
1304 (setq ret
(cdr item
))
1306 ;; FIXME: `ret' unused.
1307 ;; Should we return it here?
1310 (plain (or (eval default
) (read-passwd prompt
))))
1311 ;; ask if we don't know what to do (in which case
1312 ;; auth-source-netrc-use-gpg-tokens must be a list)
1314 (setq gpg-encrypt
(if (y-or-n-p ep
) 'gpg
'never
))
1315 ;; TODO: save the defcustom now? or ask?
1316 (setq auth-source-netrc-use-gpg-tokens
1317 (cons `(,file
,gpg-encrypt
)
1318 auth-source-netrc-use-gpg-tokens
)))
1319 (if (eq gpg-encrypt
'gpg
)
1320 (auth-source-epa-make-gpg-token plain file
)
1322 (if (stringp default
)
1323 (read-string (if (string-match ": *\\'" prompt
)
1324 (concat (substring prompt
0 (match-beginning 0))
1325 " (default " default
"): ")
1326 (concat prompt
"(default " default
") "))
1331 (setq artificial
(plist-put artificial
1332 (auth-source--symbol-keyword r
)
1338 ;; When r is not an empty string...
1339 (when (and (stringp data
)
1340 (< 0 (length data
)))
1341 ;; this function is not strictly necessary but I think it
1342 ;; makes the code clearer -tzz
1343 (let ((printer (lambda ()
1344 ;; append the key (the symbol name of r)
1345 ;; and the value in r
1348 (if (zerop (length add
)) "" " ")
1349 ;; remap auth-source tokens to netrc
1354 (port "port") ; redundant but clearer
1355 (t (symbol-name r
)))
1356 (if (string-match "[\"# ]" data
)
1359 (setq add
(concat add
(funcall printer
)))))))
1366 (lambda () (auth-source-netrc-saver file add
))))
1370 (defun auth-source-netrc-saver (file add
)
1371 "Save a line ADD in FILE, prompting along the way.
1372 Respects `auth-source-save-behavior'. Uses
1373 `auth-source-netrc-cache' to avoid prompting more than once."
1374 (let* ((key (format "%s %s" file
(rfc2104-hash 'md5
64 16 file add
)))
1375 (cached (assoc key auth-source-netrc-cache
)))
1378 (auth-source-do-trivia
1379 "auth-source-netrc-saver: found previous run for key %s, returning"
1382 (when (file-exists-p file
)
1383 (insert-file-contents file
))
1384 (when auth-source-gpg-encrypt-to
1385 ;; (see bug#7487) making `epa-file-encrypt-to' local to
1386 ;; this buffer lets epa-file skip the key selection query
1387 ;; (see the `local-variable-p' check in
1388 ;; `epa-file-write-region').
1389 (unless (local-variable-p 'epa-file-encrypt-to
(current-buffer))
1390 (make-local-variable 'epa-file-encrypt-to
))
1391 (if (listp auth-source-gpg-encrypt-to
)
1392 (setq epa-file-encrypt-to auth-source-gpg-encrypt-to
)))
1393 ;; we want the new data to be found first, so insert at beginning
1394 (goto-char (point-min))
1396 ;; Ask AFTER we've successfully opened the file.
1397 (let ((prompt (format "Save auth info to file %s? " file
))
1398 (done (not (eq auth-source-save-behavior
'ask
)))
1399 (bufname "*auth-source Help*")
1402 (setq k
(auth-source-read-char-choice prompt
'(?y ?n ?N ?e ??
)))
1406 (with-output-to-temp-buffer bufname
1408 (concat "(y)es, save\n"
1409 "(n)o but use the info\n"
1410 "(N)o and don't ask to save again\n"
1412 "(?) for help as you can see.\n"))
1413 ;; Why? Doesn't with-output-to-temp-buffer already do
1414 ;; the exact same thing anyway? --Stef
1415 (set-buffer standard-output
)
1422 (customize-save-variable 'auth-source-save-behavior nil
))
1423 (?e
(setq add
(read-string "Line to add: " add
)))
1426 (when (get-buffer-window bufname
)
1427 (delete-window (get-buffer-window bufname
)))
1429 ;; Make sure the info is not saved.
1430 (when (null auth-source-save-behavior
)
1433 (when (< 0 (length add
))
1438 (write-region (point-min) (point-max) file nil
'silent
)
1439 ;; Make the .authinfo file non-world-readable.
1440 (set-file-modes file
#o600
)
1441 (auth-source-do-debug
1442 "auth-source-netrc-create: wrote 1 new line to %s"
1444 (message "Saved new authentication information to %s" file
)
1446 (auth-source--aput auth-source-netrc-cache key
"ran"))))
1448 ;;; Backend specific parsing: Secrets API backend
1450 (defun auth-source-secrets-listify-pattern (pattern)
1451 "Convert a pattern with lists to a list of string patterns.
1453 auth-source patterns can have values of the form :foo (\"bar\"
1454 \"qux\"), which means to match any secret with :foo equal to
1455 \"bar\" or :foo equal to \"qux\". The secrets backend supports
1456 only string values for patterns, so this routine returns a list
1457 of patterns that is equivalent to the single original pattern
1458 when interpreted such that if a secret matches any pattern in the
1459 list, it matches the original pattern."
1462 (let* ((key (pop pattern
))
1463 (value (pop pattern
))
1464 (tails (auth-source-secrets-listify-pattern pattern
))
1465 (heads (if (stringp value
)
1466 (list (list key value
))
1467 (mapcar (lambda (v) (list key v
)) value
))))
1468 (cl-loop for h in heads
1469 nconc
(cl-loop for tl in tails collect
(append h tl
))))))
1471 (cl-defun auth-source-secrets-search (&rest spec
1472 &key backend create delete label max
1474 "Search the Secrets API; spec is like `auth-source'.
1476 The :label key specifies the item's label. It is the only key
1477 that can specify a substring. Any :label value besides a string
1478 will allow any label.
1480 All other search keys must match exactly. If you need substring
1481 matching, do a wider search and narrow it down yourself.
1483 You'll get back all the properties of the token as a plist.
1485 Here's an example that looks for the first item in the `Login'
1488 (let ((auth-sources \\='(\"secrets:Login\")))
1489 (auth-source-search :max 1)
1491 Here's another that looks for the first item in the `Login'
1492 Secrets collection whose label contains `gnus':
1494 (let ((auth-sources \\='(\"secrets:Login\")))
1495 (auth-source-search :max 1 :label \"gnus\")
1497 And this one looks for the first item in the `Login' Secrets
1498 collection that's a Google Chrome entry for the git.gnus.org site
1499 authentication tokens:
1501 (let ((auth-sources \\='(\"secrets:Login\")))
1502 (auth-source-search :max 1 :signon_realm \"https://git.gnus.org/Git\"))
1506 (cl-assert (not create
) nil
1507 "The Secrets API auth-source backend doesn't support creation yet")
1509 ;; (secrets-delete-item coll elt)
1510 (cl-assert (not delete
) nil
1511 "The Secrets API auth-source backend doesn't support deletion yet")
1513 (let* ((coll (oref backend source
))
1514 (max (or max
5000)) ; sanity check: default to stop at 5K
1515 (ignored-keys '(:create
:delete
:max
:backend
:label
:require
:type
))
1516 (search-keys (cl-loop for i below
(length spec
) by
2
1517 unless
(memq (nth i spec
) ignored-keys
)
1518 collect
(nth i spec
)))
1519 ;; build a search spec without the ignored keys
1520 ;; if a search key is nil or t (match anything), we skip it
1521 (search-specs (auth-source-secrets-listify-pattern
1522 (apply #'append
(mapcar
1524 (if (or (null (plist-get spec k
))
1525 (eq t
(plist-get spec k
)))
1527 (list k
(plist-get spec k
))))
1529 ;; needed keys (always including host, login, port, and secret)
1530 (returned-keys (delete-dups (append
1531 '(:host
:login
:port
:secret
)
1535 for search-spec in search-specs
1537 (cl-loop for item in
(apply #'secrets-search-items coll search-spec
)
1538 unless
(and (stringp label
)
1539 (not (string-match label item
)))
1541 ;; TODO: respect max in `secrets-search-items', not after the fact
1542 (items (butlast items
(- (length items
) max
)))
1543 ;; convert the item name to a full plist
1544 (items (mapcar (lambda (item)
1546 ;; make an entry for the secret (password) element
1549 (let ((v (secrets-get-secret coll item
)))
1551 ;; rewrite the entry from ((k1 v1) (k2 v2)) to plist
1553 (mapcar (lambda (entry)
1554 (list (car entry
) (cdr entry
)))
1555 (secrets-get-attributes coll item
)))))
1557 ;; ensure each item has each key in `returned-keys'
1558 (items (mapcar (lambda (plist)
1561 (mapcar (lambda (req)
1562 (if (plist-get plist req
)
1570 (defun auth-source-secrets-create (&rest spec
)
1572 ;; (apply 'secrets-create-item (auth-get-source entry) name passwd spec)
1575 ;;; Backend specific parsing: Mac OS Keychain (using /usr/bin/security) backend
1577 (cl-defun auth-source-macos-keychain-search (&rest spec
1578 &key backend create delete type max
1580 "Search the macOS Keychain; spec is like `auth-source'.
1582 All search keys must match exactly. If you need substring
1583 matching, do a wider search and narrow it down yourself.
1585 You'll get back all the properties of the token as a plist.
1587 The :type key is either `macos-keychain-internet' or
1588 `macos-keychain-generic'.
1590 For the internet keychain type, the :label key searches the
1591 item's labels (\"-l LABEL\" passed to \"/usr/bin/security\").
1592 Similarly, :host maps to \"-s HOST\", :user maps to \"-a USER\",
1593 and :port maps to \"-P PORT\" or \"-r PROT\"
1594 \(note PROT has to be a 4-character string).
1596 For the generic keychain type, the :label key searches the item's
1597 labels (\"-l LABEL\" passed to \"/usr/bin/security\").
1598 Similarly, :host maps to \"-c HOST\" (the \"creator\" keychain
1599 field), :user maps to \"-a USER\", and :port maps to \"-s PORT\".
1601 Here's an example that looks for the first item in the default
1602 generic macOS Keychain:
1604 (let ((auth-sources \\='(macos-keychain-generic)))
1605 (auth-source-search :max 1)
1607 Here's another that looks for the first item in the internet
1608 macOS Keychain collection whose label is `gnus':
1610 (let ((auth-sources \\='(macos-keychain-internet)))
1611 (auth-source-search :max 1 :label \"gnus\")
1613 And this one looks for the first item in the internet keychain
1614 entries for git.gnus.org:
1616 (let ((auth-sources \\='(macos-keychain-internet\")))
1617 (auth-source-search :max 1 :host \"git.gnus.org\"))
1620 (cl-assert (not create
) nil
1621 "The macOS Keychain auth-source backend doesn't support creation yet")
1623 ;; (macos-keychain-delete-item coll elt)
1624 (cl-assert (not delete
) nil
1625 "The macOS Keychain auth-source backend doesn't support deletion yet")
1627 (let* ((coll (oref backend source
))
1628 (max (or max
5000)) ; sanity check: default to stop at 5K
1629 ;; Filter out ignored keys from the spec
1630 (ignored-keys '(:create
:delete
:max
:backend
:label
:host
:port
))
1631 ;; Build a search spec without the ignored keys
1632 ;; FIXME make this loop a function? it's used in at least 3 places
1633 (search-keys (cl-loop for i below
(length spec
) by
2
1634 unless
(memq (nth i spec
) ignored-keys
)
1635 collect
(nth i spec
)))
1636 ;; If a search key value is nil or t (match anything), we skip it
1637 (search-spec (apply #'append
(mapcar
1639 (if (or (null (plist-get spec k
))
1640 (eq t
(plist-get spec k
)))
1642 (list k
(plist-get spec k
))))
1644 ;; needed keys (always including host, login, port, and secret)
1645 (returned-keys (delete-dups (append
1646 '(:host
:login
:port
:secret
)
1648 ;; Extract host and port from spec
1649 (hosts (plist-get spec
:host
))
1650 (hosts (if (and hosts
(listp hosts
)) hosts
`(,hosts
)))
1651 (ports (plist-get spec
:port
))
1652 (ports (if (and ports
(listp ports
)) ports
`(,ports
)))
1653 ;; Loop through all combinations of host/port and pass each of these to
1654 ;; auth-source-macos-keychain-search-items
1655 (items (catch 'match
1656 (dolist (host hosts
)
1657 (dolist (port ports
)
1658 (let* ((port (if port
(format "%S" port
)))
1659 (items (apply #'auth-source-macos-keychain-search-items
1666 (throw 'match items
)))))))
1668 ;; ensure each item has each key in `returned-keys'
1669 (items (mapcar (lambda (plist)
1672 (mapcar (lambda (req)
1673 (if (plist-get plist req
)
1682 (defun auth-source--decode-octal-string (string)
1683 "Convert octal string to utf-8 string. E.g: 'a\134b' to 'a\b'"
1684 (let ((list (string-to-list string
))
1685 (size (length string
)))
1686 (decode-coding-string
1687 (apply #'unibyte-string
1688 (cl-loop for i
= 0 then
(+ i
(if (eq (nth i list
) ?
\\) 4 1))
1689 for var
= (nth i list
)
1692 collect
(string-to-number
1693 (concat (cl-subseq list
(+ i
1) (+ i
4))) 8)
1698 (cl-defun auth-source-macos-keychain-search-items (coll _type _max host port
1699 &key label type user
1701 (let* ((keychain-generic (eq type
'macos-keychain-generic
))
1702 (args `(,(if keychain-generic
1703 "find-generic-password"
1704 "find-internet-password")
1706 (ret (list :type type
)))
1708 (setq args
(append args
(list "-l" label
))))
1710 (setq args
(append args
(list (if keychain-generic
"-c" "-s") host
))))
1712 (setq args
(append args
(list "-a" user
))))
1715 (if keychain-generic
1716 (setq args
(append args
(list "-s" port
)))
1717 (setq args
(append args
(list
1718 (if (string-match "[0-9]+" port
) "-P" "-r")
1721 (unless (equal coll
"default")
1722 (setq args
(append args
(list coll
))))
1725 (apply #'call-process
"/usr/bin/security" nil t nil args
)
1726 (goto-char (point-min))
1729 ((looking-at "^password: \\(?:0x[0-9A-F]+\\)? *\"\\(.+\\)\"")
1730 (setq ret
(auth-source-macos-keychain-result-append
1734 (let ((v (auth-source--decode-octal-string
1737 ;; TODO: check if this is really the label
1738 ;; match 0x00000007 <blob>="AppleID"
1740 "^[ ]+0x00000007 <blob>=\\(?:0x[0-9A-F]+\\)? *\"\\(.+\\)\"")
1741 (setq ret
(auth-source-macos-keychain-result-append
1745 (auth-source--decode-octal-string (match-string 1)))))
1746 ;; match "crtr"<uint32>="aapl"
1747 ;; match "svce"<blob>="AppleID"
1749 "^[ ]+\"\\([a-z]+\\)\"[^=]+=\\(?:0x[0-9A-F]+\\)? *\"\\(.+\\)\"")
1750 (setq ret
(auth-source-macos-keychain-result-append
1753 (auth-source--decode-octal-string (match-string 1))
1754 (auth-source--decode-octal-string (match-string 2))))))
1756 ;; return `ret' iff it has the :secret key
1757 (and (plist-get ret
:secret
) (list ret
))))
1759 (defun auth-source-macos-keychain-result-append (result generic k v
)
1761 (push (auth-source--symbol-keyword
1763 ((equal k
"acct") "user")
1764 ;; for generic keychains, creator is host, service is port
1765 ((and generic
(equal k
"crtr")) "host")
1766 ((and generic
(equal k
"svce")) "port")
1767 ;; for internet keychains, protocol is port, server is host
1768 ((and (not generic
) (equal k
"ptcl")) "port")
1769 ((and (not generic
) (equal k
"srvr")) "host")
1773 (defun auth-source-macos-keychain-create (&rest spec
)
1777 ;;; Backend specific parsing: PLSTORE backend
1779 (cl-defun auth-source-plstore-search (&rest spec
1780 &key backend create delete max
1782 "Search the PLSTORE; spec is like `auth-source'."
1783 (let* ((store (oref backend data
))
1784 (max (or max
5000)) ; sanity check: default to stop at 5K
1785 (ignored-keys '(:create
:delete
:max
:backend
:label
:require
:type
))
1786 (search-keys (cl-loop for i below
(length spec
) by
2
1787 unless
(memq (nth i spec
) ignored-keys
)
1788 collect
(nth i spec
)))
1789 ;; build a search spec without the ignored keys
1790 ;; if a search key is nil or t (match anything), we skip it
1791 (search-spec (apply #'append
(mapcar
1793 (let ((v (plist-get spec k
)))
1801 ;; needed keys (always including host, login, port, and secret)
1802 (returned-keys (delete-dups (append
1803 '(:host
:login
:port
:secret
)
1805 (items (plstore-find store search-spec
))
1806 (item-names (mapcar #'car items
))
1807 (items (butlast items
(- (length items
) max
)))
1808 ;; convert the item to a full plist
1809 (items (mapcar (lambda (item)
1810 (let* ((plist (copy-tree (cdr item
)))
1811 (secret (plist-member plist
:secret
)))
1815 (let ((v (car (cdr secret
))))
1819 ;; ensure each item has each key in `returned-keys'
1820 (items (mapcar (lambda (plist)
1823 (mapcar (lambda (req)
1824 (if (plist-get plist req
)
1831 ;; if we need to create an entry AND none were found to match
1835 ;; create based on the spec and record the value
1837 ;; if the user did not want to create the entry
1838 ;; in the file, it will be returned
1839 (apply (slot-value backend
'create-function
) spec
)
1840 ;; if not, we do the search again without :create
1841 ;; to get the updated data.
1843 ;; the result will be returned, even if the search fails
1844 (apply #'auth-source-plstore-search
1845 (plist-put spec
:create nil
)))))
1848 (dolist (item-name item-names
)
1849 (plstore-delete store item-name
))
1850 (plstore-save store
)))
1853 (cl-defun auth-source-plstore-create (&rest spec
1854 &key backend host port create
1856 (let* ((base-required '(host user port secret
))
1857 (base-secret '(secret))
1858 ;; we know (because of an assertion in auth-source-search) that the
1859 ;; :create parameter is either t or a list (which includes nil)
1860 (create-extra (if (eq t create
) nil create
))
1861 (current-data (car (auth-source-search :max
1
1864 (required (append base-required create-extra
))
1865 ;; `valist' is an alist
1867 ;; `artificial' will be returned if no creation is needed
1871 ;; only for base required elements (defined as function parameters):
1872 ;; fill in the valist with whatever data we may have from the search
1873 ;; we complete the first value if it's a list and use the value otherwise
1874 (dolist (br base-required
)
1875 (let ((val (plist-get spec
(auth-source--symbol-keyword br
))))
1877 (let ((br-choice (cond
1878 ;; all-accepting choice (predicate is t)
1880 ;; just the value otherwise
1883 (auth-source--aput valist br br-choice
))))))
1885 ;; for extra required elements, see if the spec includes a value for them
1886 (dolist (er create-extra
)
1887 (let ((k (auth-source--symbol-keyword er
))
1888 (keys (cl-loop for i below
(length spec
) by
2
1889 collect
(nth i spec
))))
1891 (auth-source--aput valist er
(plist-get spec k
)))))
1893 ;; for each required element
1894 (dolist (r required
)
1895 (let* ((data (auth-source--aget valist r
))
1896 ;; take the first element if the data is a list
1897 (data (or (auth-source-netrc-element-or-first data
)
1898 (plist-get current-data
1899 (auth-source--symbol-keyword r
))))
1900 ;; this is the default to be offered
1901 (given-default (auth-source--aget
1902 auth-source-creation-defaults r
))
1903 ;; the default supplementals are simple:
1904 ;; for the user, try `given-default' and then (user-login-name);
1905 ;; otherwise take `given-default'
1907 ((and (not given-default
) (eq r
'user
))
1910 (printable-defaults (list
1913 (auth-source-netrc-element-or-first
1914 (auth-source--aget valist
'user
))
1915 (plist-get artificial
:user
)
1919 (auth-source-netrc-element-or-first
1920 (auth-source--aget valist
'host
))
1921 (plist-get artificial
:host
)
1925 (auth-source-netrc-element-or-first
1926 (auth-source--aget valist
'port
))
1927 (plist-get artificial
:port
)
1929 (prompt (or (auth-source--aget auth-source-creation-prompts r
)
1931 (secret "%p password for %u@%h: ")
1932 (user "%p user name for %h: ")
1933 (host "%p host name for user %u: ")
1934 (port "%p port for %u@%h: "))
1935 (format "Enter %s (%%u@%%h:%%p): " r
)))
1936 (prompt (auth-source-format-prompt
1938 `((?u
,(auth-source--aget printable-defaults
'user
))
1939 (?h
,(auth-source--aget printable-defaults
'host
))
1940 (?p
,(auth-source--aget printable-defaults
'port
))))))
1942 ;; Store the data, prompting for the password if needed.
1945 (or (eval default
) (read-passwd prompt
))
1946 (if (stringp default
)
1948 (if (string-match ": *\\'" prompt
)
1949 (concat (substring prompt
0 (match-beginning 0))
1950 " (default " default
"): ")
1951 (concat prompt
"(default " default
") "))
1956 (if (member r base-secret
)
1957 (setq secret-artificial
1958 (plist-put secret-artificial
1959 (auth-source--symbol-keyword r
)
1961 (setq artificial
(plist-put artificial
1962 (auth-source--symbol-keyword r
)
1964 (plstore-put (oref backend data
)
1965 (sha1 (format "%s@%s:%s"
1966 (plist-get artificial
:user
)
1967 (plist-get artificial
:host
)
1968 (plist-get artificial
:port
)))
1969 artificial secret-artificial
)
1970 (if (y-or-n-p (format "Save auth info to file %s? "
1971 (plstore-get-file (oref backend data
))))
1972 (plstore-save (oref backend data
)))))
1976 ;; (auth-source-user-or-password '("login" "password") "imap.myhost.com" t "tzz")
1978 ;; deprecate the old interface
1979 (make-obsolete 'auth-source-user-or-password
1980 'auth-source-search
"Emacs 24.1")
1981 (make-obsolete 'auth-source-forget-user-or-password
1982 'auth-source-forget
"Emacs 24.1")
1984 (defun auth-source-user-or-password
1985 (mode host port
&optional username create-missing delete-existing
)
1986 "Find MODE (string or list of strings) matching HOST and PORT.
1988 DEPRECATED in favor of `auth-source-search'!
1990 USERNAME is optional and will be used as \"login\" in a search
1991 across the Secret Service API (see secrets.el) if the resulting
1992 items don't have a username. This means that if you search for
1993 username \"joe\" and it matches an item but the item doesn't have
1994 a :user attribute, the username \"joe\" will be returned.
1996 A non nil DELETE-EXISTING means deleting any matching password
1997 entry in the respective sources. This is useful only when
1998 CREATE-MISSING is non nil as well; the intended use case is to
1999 remove wrong password entries.
2001 If no matching entry is found, and CREATE-MISSING is non nil,
2002 the password will be retrieved interactively, and it will be
2003 stored in the password database which matches best (see
2006 MODE can be \"login\" or \"password\"."
2007 (auth-source-do-debug
2008 "auth-source-user-or-password: DEPRECATED get %s for %s (%s) + user=%s"
2009 mode host port username
)
2011 (let* ((listy (listp mode
))
2012 (mode (if listy mode
(list mode
)))
2013 ;; (cname (if username
2014 ;; (format "%s %s:%s %s" mode host port username)
2015 ;; (format "%s %s:%s" mode host port)))
2016 (search (list :host host
:port port
))
2017 (search (if username
(append search
(list :user username
)) search
))
2018 (search (if create-missing
2019 (append search
(list :create t
))
2021 (search (if delete-existing
2022 (append search
(list :delete t
))
2024 ;; (found (if (not delete-existing)
2025 ;; (gethash cname auth-source-cache)
2026 ;; (remhash cname auth-source-cache)
2031 (auth-source-do-debug
2032 "auth-source-user-or-password: DEPRECATED cached %s=%s for %s (%s) + %s"
2034 ;; don't show the password
2035 (if (and (member "password" mode
) t
)
2039 found
) ; return the found data
2040 ;; else, if not found, search with a max of 1
2041 (let ((choice (nth 0 (apply #'auth-source-search
2042 (append '(:max
1) search
)))))
2046 ((equal "password" m
)
2047 (push (if (plist-get choice
:secret
)
2048 (funcall (plist-get choice
:secret
))
2051 (push (plist-get choice
:user
) found
)))))
2052 (setq found
(nreverse found
))
2053 (setq found
(if listy found
(car-safe found
)))))
2057 (defun auth-source-user-and-password (host &optional user
)
2058 (let* ((auth-info (car
2064 :require
'(:user
:secret
)
2069 :require
'(:user
:secret
)
2071 (user (plist-get auth-info
:user
))
2072 (password (plist-get auth-info
:secret
)))
2073 (when (functionp password
)
2074 (setq password
(funcall password
)))
2075 (list user password auth-info
)))
2077 (provide 'auth-source
)
2079 ;;; auth-source.el ends here