1 ;;; auth-source.el --- authentication sources for Gnus and Emacs
3 ;; Copyright (C) 2008-2015 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)
46 (eval-when-compile (require 'cl))
48 (or (ignore-errors (require 'eieio))
49 ;; gnus-fallback-lib/ from gnus/lisp/gnus-fallback-lib
51 (let ((load-path (cons (expand-file-name
52 "gnus-fallback-lib/eieio"
53 (file-name-directory (locate-library "gnus")))
57 "eieio not found in `load-path' or gnus-fallback-lib/ directory.")))
59 (autoload 'secrets-create-item "secrets")
60 (autoload 'secrets-delete-item "secrets")
61 (autoload 'secrets-get-alias "secrets")
62 (autoload 'secrets-get-attributes "secrets")
63 (autoload 'secrets-get-secret "secrets")
64 (autoload 'secrets-list-collections "secrets")
65 (autoload 'secrets-search-items "secrets")
67 (autoload 'rfc2104-hash "rfc2104")
69 (autoload 'plstore-open "plstore")
70 (autoload 'plstore-find "plstore")
71 (autoload 'plstore-put "plstore")
72 (autoload 'plstore-delete "plstore")
73 (autoload 'plstore-save "plstore")
74 (autoload 'plstore-get-file "plstore")
76 (autoload 'epg-make-context "epg")
77 (autoload 'epg-context-set-passphrase-callback "epg")
78 (autoload 'epg-decrypt-string "epg")
79 (autoload 'epg-encrypt-string "epg")
80 (autoload 'epg-context-set-armor "epg")
82 (autoload 'help-mode "help-mode" nil t)
84 (defvar secrets-enabled)
86 (defgroup auth-source nil
87 "Authentication sources."
88 :version "23.1" ;; No Gnus
92 (defcustom auth-source-cache-expiry 7200
93 "How many seconds passwords are cached, or nil to disable
94 expiring. Overrides `password-cache-expiry' through a
98 :type '(choice (const :tag "Never" nil)
99 (const :tag "All Day" 86400)
100 (const :tag "2 Hours" 7200)
101 (const :tag "30 Minutes" 1800)
102 (integer :tag "Seconds")))
104 ;; The slots below correspond with the `auth-source-search' spec,
105 ;; so a backend with :host set, for instance, would match only
106 ;; searches for that host. Normally they are nil.
107 (defclass auth-source-backend ()
108 ((type :initarg :type
112 :documentation "The backend type.")
113 (source :initarg :source
116 :documentation "The backend source.")
121 :documentation "The backend host.")
126 :documentation "The backend user.")
131 :documentation "The backend protocol.")
134 :documentation "Internal backend data.")
135 (create-function :initarg :create-function
139 :documentation "The create function.")
140 (search-function :initarg :search-function
144 :documentation "The search function.")))
146 (defcustom auth-source-protocols '((imap "imap" "imaps" "143" "993")
147 (pop3 "pop3" "pop" "pop3s" "110" "995")
151 "List of authentication protocols and their names"
154 :version "23.2" ;; No Gnus
155 :type '(repeat :tag "Authentication Protocols"
156 (cons :tag "Protocol Entry"
157 (symbol :tag "Protocol")
159 (string :tag "Name")))))
161 ;; Generate all the protocols in a format Customize can use.
162 ;; TODO: generate on the fly from auth-source-protocols
163 (defconst auth-source-protocols-customize
165 (let ((p (car-safe a)))
167 :tag (upcase (symbol-name p))
169 auth-source-protocols))
171 (defvar auth-source-creation-defaults nil
172 ;; FIXME: AFAICT this is not set (or let-bound) anywhere!
173 "Defaults for creating token values. Usually let-bound.")
175 (defvar auth-source-creation-prompts nil
176 "Default prompts for token values. Usually let-bound.")
178 (make-obsolete 'auth-source-hide-passwords nil "Emacs 24.1")
180 (defcustom auth-source-save-behavior 'ask
181 "If set, auth-source will respect it for save behavior."
183 :version "23.2" ;; No Gnus
185 :tag "auth-source new token save behavior"
186 (const :tag "Always save" t)
187 (const :tag "Never save" nil)
188 (const :tag "Ask" ask)))
190 ;; 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)))
191 ;; TODO: or maybe leave as (setq auth-source-netrc-use-gpg-tokens 'never)
193 (defcustom auth-source-netrc-use-gpg-tokens 'never
194 "Set this to tell auth-source when to create GPG password
195 tokens in netrc files. It's either an alist or `never'.
196 Note that if EPA/EPG is not available, this should NOT be used."
198 :version "23.2" ;; No Gnus
200 (const :tag "Always use GPG password tokens" (t gpg))
201 (const :tag "Never use GPG password tokens" never)
202 (repeat :tag "Use a lookup list"
204 (choice :tag "Matcher"
205 (const :tag "Match anything" t)
206 (const :tag "The EPA encrypted file extensions"
207 ,(if (boundp 'epa-file-auto-mode-alist-entry)
208 (car epa-file-auto-mode-alist-entry)
210 (regexp :tag "Regular expression"))
211 (choice :tag "What to do"
212 (const :tag "Save GPG-encrypted password tokens" gpg)
213 (const :tag "Don't encrypt tokens" never))))))
215 (defvar auth-source-magic "auth-source-magic ")
217 (defcustom auth-source-do-cache t
218 "Whether auth-source should cache information with `password-cache'."
220 :version "23.2" ;; No Gnus
223 (defcustom auth-source-debug nil
224 "Whether auth-source should log debug messages.
226 If the value is nil, debug messages are not logged.
228 If the value is t, debug messages are logged with `message'. In
229 that case, your authentication data will be in the clear (except
232 If the value is a function, debug messages are logged by calling
233 that function using the same arguments as `message'."
235 :version "23.2" ;; No Gnus
237 :tag "auth-source debugging mode"
238 (const :tag "Log using `message' to the *Messages* buffer" t)
239 (const :tag "Log all trivia with `message' to the *Messages* buffer"
241 (function :tag "Function that takes arguments like `message'")
242 (const :tag "Don't log anything" nil)))
244 (defcustom auth-sources '("~/.authinfo" "~/.authinfo.gpg" "~/.netrc")
245 "List of authentication sources.
246 Each entry is the authentication type with optional properties.
247 Entries are tried in the order in which they appear.
248 See Info node `(auth)Help for users' for details.
250 If an entry names a file with the \".gpg\" extension and you have
251 EPA/EPG set up, the file will be encrypted and decrypted
252 automatically. See Info node `(epa)Encrypting/decrypting gpg files'
255 It's best to customize this with `\\[customize-variable]' because the choices
256 can get pretty complex."
258 :version "24.1" ;; No Gnus
259 :type `(repeat :tag "Authentication Sources"
261 (string :tag "Just a file")
262 (const :tag "Default Secrets API Collection" default)
263 (const :tag "Login Secrets API Collection" "secrets:Login")
264 (const :tag "Temp Secrets API Collection" "secrets:session")
266 (const :tag "Default internet Mac OS Keychain"
267 macos-keychain-internet)
269 (const :tag "Default generic Mac OS Keychain"
270 macos-keychain-generic)
272 (list :tag "Source definition"
273 (const :format "" :value :source)
274 (choice :tag "Authentication backend choice"
275 (string :tag "Authentication Source (file)")
277 :tag "Secret Service API/KWallet/GNOME Keyring"
278 (const :format "" :value :secrets)
279 (choice :tag "Collection to use"
280 (string :tag "Collection name")
281 (const :tag "Default" default)
282 (const :tag "Login" "Login")
284 :tag "Temporary" "session")))
286 :tag "Mac OS internet Keychain"
288 :value :macos-keychain-internet)
289 (choice :tag "Collection to use"
290 (string :tag "internet Keychain path")
291 (const :tag "default" default)))
293 :tag "Mac OS generic Keychain"
295 :value :macos-keychain-generic)
296 (choice :tag "Collection to use"
297 (string :tag "generic Keychain path")
298 (const :tag "default" default))))
299 (repeat :tag "Extra Parameters" :inline t
300 (choice :tag "Extra parameter"
303 (const :format "" :value :host)
304 (choice :tag "Host (machine) choice"
307 :tag "Regular expression")))
310 (const :format "" :value :port)
314 ,@auth-source-protocols-customize))
315 (list :tag "User" :inline t
316 (const :format "" :value :user)
318 :tag "Personality/Username"
323 (defcustom auth-source-gpg-encrypt-to t
324 "List of recipient keys that `authinfo.gpg' encrypted to.
325 If the value is not a list, symmetric encryption will be used."
327 :version "24.1" ;; No Gnus
328 :type '(choice (const :tag "Symmetric encryption" t)
329 (repeat :tag "Recipient public keys"
330 (string :tag "Recipient public key"))))
332 ;; temp for debugging
333 ;; (unintern 'auth-source-protocols)
334 ;; (unintern 'auth-sources)
335 ;; (customize-variable 'auth-sources)
336 ;; (setq auth-sources nil)
337 ;; (format "%S" auth-sources)
338 ;; (customize-variable 'auth-source-protocols)
339 ;; (setq auth-source-protocols nil)
340 ;; (format "%S" auth-source-protocols)
341 ;; (auth-source-pick nil :host "a" :port 'imap)
342 ;; (auth-source-user-or-password "login" "imap.myhost.com" 'imap)
343 ;; (auth-source-user-or-password "password" "imap.myhost.com" 'imap)
344 ;; (auth-source-user-or-password-imap "login" "imap.myhost.com")
345 ;; (auth-source-user-or-password-imap "password" "imap.myhost.com")
346 ;; (auth-source-protocol-defaults 'imap)
348 ;; (let ((auth-source-debug 'debug)) (auth-source-do-debug "hello"))
349 ;; (let ((auth-source-debug t)) (auth-source-do-debug "hello"))
350 ;; (let ((auth-source-debug nil)) (auth-source-do-debug "hello"))
351 (defun auth-source-do-debug (&rest msg)
352 (when auth-source-debug
353 (apply #'auth-source-do-warn msg)))
355 (defun auth-source-do-trivia (&rest msg)
356 (when (or (eq auth-source-debug 'trivia)
357 (functionp auth-source-debug))
358 (apply #'auth-source-do-warn msg)))
360 (defun auth-source-do-warn (&rest msg)
362 ;; set logger to either the function in auth-source-debug or 'message
363 ;; note that it will be 'message if auth-source-debug is nil
364 (if (functionp auth-source-debug)
370 ;; (auth-source-read-char-choice "enter choice? " '(?a ?b ?q))
371 (defun auth-source-read-char-choice (prompt choices)
372 "Read one of CHOICES by `read-char-choice', or `read-char'.
373 `dropdown-list' support is disabled because it doesn't work reliably.
374 Only one of CHOICES will be returned. The PROMPT is augmented
375 with \"[a/b/c] \" if CHOICES is \(?a ?b ?c)."
377 (let* ((prompt-choices
378 (apply #'concat (loop for c in choices
379 collect (format "%c/" c))))
380 (prompt-choices (concat "[" (substring prompt-choices 0 -1) "] "))
381 (full-prompt (concat prompt prompt-choices))
384 (while (not (memq k choices))
386 ((fboundp 'read-char-choice)
387 (read-char-choice full-prompt choices))
388 (t (message "%s" full-prompt)
389 (setq k (read-char))))))
392 ;; (auth-source-pick nil :host "any" :port 'imap :user "joe")
393 ;; (auth-source-pick t :host "any" :port 'imap :user "joe")
394 ;; (setq auth-sources '((:source (:secrets default) :host t :port t :user "joe")
395 ;; (:source (:secrets "session") :host t :port t :user "joe")
396 ;; (:source (:secrets "Login") :host t :port t)
397 ;; (:source "~/.authinfo.gpg" :host t :port t)))
399 ;; (setq auth-sources '((:source (:secrets default) :host t :port t :user "joe")
400 ;; (:source (:secrets "session") :host t :port t :user "joe")
401 ;; (:source (:secrets "Login") :host t :port t)
404 ;; (setq auth-sources '((:source "~/.authinfo.gpg" :host t :port t)))
406 ;; (auth-source-backend-parse "myfile.gpg")
407 ;; (auth-source-backend-parse 'default)
408 ;; (auth-source-backend-parse "secrets:Login")
409 ;; (auth-source-backend-parse 'macos-keychain-internet)
410 ;; (auth-source-backend-parse 'macos-keychain-generic)
411 ;; (auth-source-backend-parse "macos-keychain-internet:/path/here.keychain")
412 ;; (auth-source-backend-parse "macos-keychain-generic:/path/here.keychain")
414 (defun auth-source-backend-parse (entry)
415 "Creates an auth-source-backend from an ENTRY in `auth-sources'."
416 (auth-source-backend-parse-parameters
419 ;; take 'default and recurse to get it as a Secrets API default collection
420 ;; matching any user, host, and protocol
422 (auth-source-backend-parse '(:source (:secrets default))))
423 ;; take secrets:XYZ and recurse to get it as Secrets API collection "XYZ"
424 ;; matching any user, host, and protocol
425 ((and (stringp entry) (string-match "^secrets:\\(.+\\)" entry))
426 (auth-source-backend-parse `(:source (:secrets ,(match-string 1 entry)))))
428 ;; take 'macos-keychain-internet and recurse to get it as a Mac OS
429 ;; Keychain collection matching any user, host, and protocol
430 ((eq entry 'macos-keychain-internet)
431 (auth-source-backend-parse '(:source (:macos-keychain-internet default))))
432 ;; take 'macos-keychain-generic and recurse to get it as a Mac OS
433 ;; Keychain collection matching any user, host, and protocol
434 ((eq entry 'macos-keychain-generic)
435 (auth-source-backend-parse '(:source (:macos-keychain-generic default))))
436 ;; take macos-keychain-internet:XYZ and recurse to get it as MacOS
437 ;; Keychain "XYZ" matching any user, host, and protocol
438 ((and (stringp entry) (string-match "^macos-keychain-internet:\\(.+\\)"
440 (auth-source-backend-parse `(:source (:macos-keychain-internet
441 ,(match-string 1 entry)))))
442 ;; take macos-keychain-generic:XYZ and recurse to get it as MacOS
443 ;; Keychain "XYZ" matching any user, host, and protocol
444 ((and (stringp entry) (string-match "^macos-keychain-generic:\\(.+\\)"
446 (auth-source-backend-parse `(:source (:macos-keychain-generic
447 ,(match-string 1 entry)))))
449 ;; take just a file name and recurse to get it as a netrc file
450 ;; matching any user, host, and protocol
452 (auth-source-backend-parse `(:source ,entry)))
454 ;; a file name with parameters
455 ((stringp (plist-get entry :source))
456 (if (equal (file-name-extension (plist-get entry :source)) "plist")
458 (plist-get entry :source)
459 :source (plist-get entry :source)
461 :search-function #'auth-source-plstore-search
462 :create-function #'auth-source-plstore-create
463 :data (plstore-open (plist-get entry :source)))
465 (plist-get entry :source)
466 :source (plist-get entry :source)
468 :search-function #'auth-source-netrc-search
469 :create-function #'auth-source-netrc-create)))
471 ;; the MacOS Keychain
473 (not (null (plist-get entry :source))) ; the source must not be nil
474 (listp (plist-get entry :source)) ; and it must be a list
476 (plist-get (plist-get entry :source) :macos-keychain-generic)
477 (plist-get (plist-get entry :source) :macos-keychain-internet)))
479 (let* ((source-spec (plist-get entry :source))
480 (keychain-generic (plist-get source-spec :macos-keychain-generic))
481 (keychain-type (if keychain-generic
482 'macos-keychain-generic
483 'macos-keychain-internet))
484 (source (plist-get source-spec (if keychain-generic
485 :macos-keychain-generic
486 :macos-keychain-internet))))
488 (when (symbolp source)
489 (setq source (symbol-name source)))
492 (format "Mac OS Keychain (%s)" source)
495 :search-function #'auth-source-macos-keychain-search
496 :create-function #'auth-source-macos-keychain-create)))
498 ;; the Secrets API. We require the package, in order to have a
499 ;; defined value for `secrets-enabled'.
501 (not (null (plist-get entry :source))) ; the source must not be nil
502 (listp (plist-get entry :source)) ; and it must be a list
503 (require 'secrets nil t) ; and we must load the Secrets API
504 secrets-enabled) ; and that API must be enabled
506 ;; the source is either the :secrets key in ENTRY or
507 ;; if that's missing or nil, it's "session"
508 (let ((source (or (plist-get (plist-get entry :source) :secrets)
511 ;; if the source is a symbol, we look for the alias named so,
512 ;; and if that alias is missing, we use "Login"
513 (when (symbolp source)
514 (setq source (or (secrets-get-alias (symbol-name source))
517 (if (featurep 'secrets)
519 (format "Secrets API (%s)" source)
522 :search-function #'auth-source-secrets-search
523 :create-function #'auth-source-secrets-create)
525 "auth-source-backend-parse: no Secrets API, ignoring spec: %S" entry)
527 (format "Ignored Secrets API (%s)" source)
534 "auth-source-backend-parse: invalid backend spec: %S" entry)
535 (make-instance 'auth-source-backend
539 (defun auth-source-backend-parse-parameters (entry backend)
540 "Fills in the extra auth-source-backend parameters of ENTRY.
541 Using the plist ENTRY, get the :host, :port, and :user search
543 (let ((entry (if (stringp entry)
547 (when (setq val (plist-get entry :host))
548 (oset backend host val))
549 (when (setq val (plist-get entry :user))
550 (oset backend user val))
551 (when (setq val (plist-get entry :port))
552 (oset backend port val)))
555 ;; (mapcar 'auth-source-backend-parse auth-sources)
557 (defun* auth-source-search (&rest spec
559 require create delete
561 "Search or modify authentication backends according to SPEC.
563 This function parses `auth-sources' for matches of the SPEC
564 plist. It can optionally create or update an authentication
565 token if requested. A token is just a standard Emacs property
566 list with a :secret property that can be a function; all the
567 other properties will always hold scalar values.
569 Typically the :secret property, if present, contains a password.
571 Common search keys are :max, :host, :port, and :user. In
572 addition, :create specifies if and how tokens will be created.
573 Finally, :type can specify which backend types you want to check.
575 A string value is always matched literally. A symbol is matched
576 as its string value, literally. All the SPEC values can be
577 single values (symbol or string) or lists thereof (in which case
578 any of the search terms matches).
580 :create t means to create a token if possible.
582 A new token will be created if no matching tokens were found.
583 The new token will have only the keys the backend requires. For
584 the netrc backend, for instance, that's the user, host, and
589 \(let ((auth-source-creation-defaults \\='((user . \"defaultUser\")
590 (A . \"default A\"))))
591 (auth-source-search :host \"mine\" :type \\='netrc :max 1
592 :P \"pppp\" :Q \"qqqq\"
597 \"Search for any entry matching host `mine' in backends of type
598 `netrc', maximum one result.
600 Create a new entry if you found none. The netrc backend will
601 automatically require host, user, and port. The host will be
602 `mine'. We prompt for the user with default `defaultUser' and
603 for the port without a default. We will not prompt for A, Q,
604 or P. The resulting token will only have keys user, host, and
607 :create \\='(A B C) also means to create a token if possible.
609 The behavior is like :create t but if the list contains any
610 parameter, that parameter will be required in the resulting
611 token. The value for that parameter will be obtained from the
612 search parameters or from user input. If any queries are needed,
613 the alist `auth-source-creation-defaults' will be checked for the
614 default value. If the user, host, or port are missing, the alist
615 `auth-source-creation-prompts' will be used to look up the
616 prompts IN THAT ORDER (so the `user' prompt will be queried first,
617 then `host', then `port', and finally `secret'). Each prompt string
618 can use %u, %h, and %p to show the user, host, and port.
622 \(let ((auth-source-creation-defaults \\='((user . \"defaultUser\")
623 (A . \"default A\")))
624 (auth-source-creation-prompts
625 \\='((password . \"Enter IMAP password for %h:%p: \"))))
626 (auth-source-search :host \\='(\"nonesuch\" \"twosuch\") :type \\='netrc :max 1
627 :P \"pppp\" :Q \"qqqq\"
628 :create \\='(A B Q)))
632 \"Search for any entry matching host `nonesuch'
633 or `twosuch' in backends of type `netrc', maximum one result.
635 Create a new entry if you found none. The netrc backend will
636 automatically require host, user, and port. The host will be
637 `nonesuch' and Q will be `qqqq'. We prompt for the password
638 with the shown prompt. We will not prompt for Q. The resulting
639 token will have keys user, host, port, A, B, and Q. It will not
640 have P with any value, even though P is used in the search to
641 find only entries that have P set to `pppp'.\"
643 When multiple values are specified in the search parameter, the
644 user is prompted for which one. So :host (X Y Z) would ask the
645 user to choose between X, Y, and Z.
647 This creation can fail if the search was not specific enough to
648 create a new token (it's up to the backend to decide that). You
649 should `catch' the backend-specific error as usual. Some
650 backends (netrc, at least) will prompt the user rather than throw
653 :require (A B C) means that only results that contain those
654 tokens will be returned. Thus for instance requiring :secret
655 will ensure that any results will actually have a :secret
658 :delete t means to delete any found entries. nil by default.
659 Use `auth-source-delete' in ELisp code instead of calling
660 `auth-source-search' directly with this parameter.
662 :type (X Y Z) will check only those backend types. `netrc' and
663 `secrets' are the only ones supported right now.
665 :max N means to try to return at most N items (defaults to 1).
666 More than N items may be returned, depending on the search and
669 When :max is 0 the function will return just t or nil to indicate
670 if any matches were found.
672 :host (X Y Z) means to match only hosts X, Y, or Z according to
673 the match rules above. Defaults to t.
675 :user (X Y Z) means to match only users X, Y, or Z according to
676 the match rules above. Defaults to t.
678 :port (P Q R) means to match only protocols P, Q, or R.
681 :K (V1 V2 V3) for any other key K will match values V1, V2, or
682 V3 (note the match rules above).
684 The return value is a list with at most :max tokens. Each token
685 is a plist with keys :backend :host :port :user, plus any other
686 keys provided by the backend (notably :secret). But note the
687 exception for :max 0, which see above.
689 The token can hold a :save-function key. If you call that, the
690 user will be prompted to save the data to the backend. You can't
691 request that this should happen right after creation, because
692 `auth-source-search' has no way of knowing if the token is
693 actually useful. So the caller must arrange to call this function.
695 The token's :secret key can hold a function. In that case you
696 must call it to obtain the actual value."
697 (let* ((backends (mapcar #'auth-source-backend-parse auth-sources))
699 (ignored-keys '(:require :create :delete :max))
700 (keys (loop for i below (length spec) by 2
701 unless (memq (nth i spec) ignored-keys)
702 collect (nth i spec)))
703 (cached (auth-source-remembered-p spec))
704 ;; note that we may have cached results but found is still nil
705 ;; (there were no results from the search)
706 (found (auth-source-recall spec))
709 (if (and cached auth-source-do-cache)
710 (auth-source-do-debug
711 "auth-source-search: found %d CACHED results matching %S"
715 (or (eq t create) (listp create)) t
716 "Invalid auth-source :create parameter (must be t or a list): %s %s")
720 "Invalid auth-source :require parameter (must be a list): %s")
722 (setq filtered-backends (copy-sequence backends))
723 (dolist (backend backends)
725 ;; ignore invalid slots
727 (unless (auth-source-search-collection
729 (slot-value backend key))
730 (setq filtered-backends (delq backend filtered-backends))
732 (invalid-slot-name nil))))
734 (auth-source-do-trivia
735 "auth-source-search: found %d backends matching %S"
736 (length filtered-backends) spec)
738 ;; (debug spec "filtered" filtered-backends)
739 ;; First go through all the backends without :create, so we can
741 (setq found (auth-source-search-backends filtered-backends
745 ;; create is always nil here
749 (auth-source-do-debug
750 "auth-source-search: found %d results (max %d) matching %S"
751 (length found) max spec)
753 ;; If we didn't find anything, then we allow the backend(s) to
754 ;; create the entries.
757 (setq found (auth-source-search-backends filtered-backends
763 (auth-source-do-debug
764 "auth-source-search: CREATED %d results (max %d) matching %S"
765 (length found) max spec))
767 ;; note we remember the lack of result too, if it's applicable
768 (when auth-source-do-cache
769 (auth-source-remember spec found)))
775 (defun auth-source-search-backends (backends spec max create delete require)
776 (let ((max (if (zerop max) 1 max)) ; stop with 1 match if we're asked for zero
778 (dolist (backend backends)
779 (when (> max (length matches)) ; if we need more matches...
780 (let* ((bmatches (apply
781 (slot-value backend 'search-function)
783 :type (slot-value backend 'type)
784 ;; note we're overriding whatever the spec
785 ;; has for :max, :require, :create, and :delete
792 (auth-source-do-trivia
793 "auth-source-search-backend: got %d (max %d) in %s:%s matching %S"
794 (length bmatches) max
795 (slot-value backend 'type)
796 (slot-value backend 'source)
798 (setq matches (append matches bmatches))))))
801 ;; (auth-source-search :max 0)
802 ;; (auth-source-search :max 1)
803 ;; (funcall (plist-get (nth 0 (auth-source-search :max 1)) :secret))
804 ;; (auth-source-search :host "nonesuch" :type 'netrc :K 1)
805 ;; (auth-source-search :host "nonesuch" :type 'secrets)
807 (defun auth-source-delete (&rest spec)
808 "Delete entries from the authentication backends according to SPEC.
809 Calls `auth-source-search' with the :delete property in SPEC set to t.
810 The backend may not actually delete the entries.
812 Returns the deleted entries."
813 (auth-source-search (plist-put spec :delete t)))
815 (defun auth-source-search-collection (collection value)
816 "Returns t is VALUE is t or COLLECTION is t or COLLECTION contains VALUE."
817 (when (and (atom collection) (not (eq t collection)))
818 (setq collection (list collection)))
820 ;; (debug :collection collection :value value)
821 (or (eq collection t)
823 (equal collection value)
824 (member value collection)))
826 (defvar auth-source-netrc-cache nil)
828 (defun auth-source-forget-all-cached ()
829 "Forget all cached auth-source data."
831 (loop for sym being the symbols of password-data
832 ;; when the symbol name starts with auth-source-magic
833 when (string-match (concat "^" auth-source-magic)
836 do (password-cache-remove (symbol-name sym)))
837 (setq auth-source-netrc-cache nil))
839 (defun auth-source-format-cache-entry (spec)
840 "Format SPEC entry to put it in the password cache."
841 (concat auth-source-magic (format "%S" spec)))
843 (defun auth-source-remember (spec found)
844 "Remember FOUND search results for SPEC."
845 (let ((password-cache-expiry auth-source-cache-expiry))
847 (auth-source-format-cache-entry spec) found)))
849 (defun auth-source-recall (spec)
850 "Recall FOUND search results for SPEC."
851 (password-read-from-cache (auth-source-format-cache-entry spec)))
853 (defun auth-source-remembered-p (spec)
854 "Check if SPEC is remembered."
856 (auth-source-format-cache-entry spec)))
858 (defun auth-source-forget (spec)
859 "Forget any cached data matching SPEC exactly.
861 This is the same SPEC you passed to `auth-source-search'.
862 Returns t or nil for forgotten or not found."
863 (password-cache-remove (auth-source-format-cache-entry spec)))
865 ;; (loop for sym being the symbols of password-data when (string-match (concat "^" auth-source-magic) (symbol-name sym)) collect (symbol-name sym))
867 ;; (auth-source-remember '(:host "wedd") '(4 5 6))
868 ;; (auth-source-remembered-p '(:host "wedd"))
869 ;; (auth-source-remember '(:host "xedd") '(1 2 3))
870 ;; (auth-source-remembered-p '(:host "xedd"))
871 ;; (auth-source-remembered-p '(:host "zedd"))
872 ;; (auth-source-recall '(:host "xedd"))
873 ;; (auth-source-recall '(:host t))
874 ;; (auth-source-forget+ :host t)
876 (defun auth-source-forget+ (&rest spec)
877 "Forget any cached data matching SPEC. Returns forgotten count.
879 This is not a full `auth-source-search' spec but works similarly.
880 For instance, \(:host \"myhost\" \"yourhost\") would find all the
881 cached data that was found with a search for those two hosts,
882 while \(:host t) would find all host entries."
885 (loop for sym being the symbols of password-data
886 ;; when the symbol name matches with auth-source-magic
887 when (and (setq sname (symbol-name sym))
888 (string-match (concat "^" auth-source-magic "\\(.+\\)")
890 ;; and the spec matches what was stored in the cache
891 (auth-source-specmatchp spec (read (match-string 1 sname))))
894 (password-cache-remove sname)
898 (defun auth-source-specmatchp (spec stored)
899 (let ((keys (loop for i below (length spec) by 2
900 collect (nth i spec))))
903 (unless (auth-source-search-collection (plist-get stored key)
904 (plist-get spec key))
908 ;; (auth-source-pick-first-password :host "z.lifelogs.com")
909 ;; (auth-source-pick-first-password :port "imap")
910 (defun auth-source-pick-first-password (&rest spec)
911 "Pick the first secret found from applying SPEC to `auth-source-search'."
912 (let* ((result (nth 0 (apply #'auth-source-search (plist-put spec :max 1))))
913 (secret (plist-get result :secret)))
915 (if (functionp secret)
919 ;; (auth-source-format-prompt "test %u %h %p" '((?u "user") (?h "host")))
920 (defun auth-source-format-prompt (prompt alist)
921 "Format PROMPT using %x (for any character x) specifiers in ALIST."
923 (let ((c (nth 0 cell))
926 (setq prompt (replace-regexp-in-string (format "%%%c" c)
931 (defun auth-source-ensure-strings (values)
932 (unless (listp values)
933 (setq values (list values)))
934 (mapcar (lambda (value)
940 ;;; Backend specific parsing: netrc/authinfo backend
942 (defun auth-source--aput-1 (alist key val)
945 (while (and (consp rest) (not (equal key (caar rest))))
946 (push (pop rest) seen))
948 (if (null rest) alist
949 (nconc (nreverse seen)
950 (if (equal key (caar rest)) (cdr rest) rest))))))
951 (defmacro auth-source--aput (var key val)
952 `(setq ,var (auth-source--aput-1 ,var ,key ,val)))
954 (defun auth-source--aget (alist key)
955 (cdr (assoc key alist)))
957 ;; (auth-source-netrc-parse :file "~/.authinfo.gpg")
958 (defun* auth-source-netrc-parse (&key file max host user port require
960 "Parse FILE and return a list of all entries in the file.
961 Note that the MAX parameter is used so we can exit the parse early."
963 ;; We got already parsed contents; just return it.
965 (when (file-exists-p file)
966 (setq port (auth-source-ensure-strings port))
968 (let* ((max (or max 5000)) ; sanity check: default to stop at 5K
970 (cached (cdr-safe (assoc file auth-source-netrc-cache)))
971 (cached-mtime (plist-get cached :mtime))
972 (cached-secrets (plist-get cached :secret))
973 (check (lambda(alist)
975 (auth-source-search-collection
978 (auth-source--aget alist "machine")
979 (auth-source--aget alist "host")
981 (auth-source-search-collection
984 (auth-source--aget alist "login")
985 (auth-source--aget alist "account")
986 (auth-source--aget alist "user")
988 (auth-source-search-collection
991 (auth-source--aget alist "port")
992 (auth-source--aget alist "protocol")
995 ;; the required list of keys is nil, or
997 ;; every element of require is in n(ormalized)
998 (let ((n (nth 0 (auth-source-netrc-normalize
999 (list alist) file))))
1000 (loop for req in require
1001 always (plist-get n req)))))))
1004 (if (and (functionp cached-secrets)
1006 (nth 5 (file-attributes file))))
1008 (auth-source-do-trivia
1009 "auth-source-netrc-parse: using CACHED file data for %s"
1011 (insert (funcall cached-secrets)))
1012 (insert-file-contents file)
1013 ;; cache all netrc files (used to be just .gpg files)
1014 ;; Store the contents of the file heavily encrypted in memory.
1015 ;; (note for the irony-impaired: they are just obfuscated)
1017 auth-source-netrc-cache file
1018 (list :mtime (nth 5 (file-attributes file))
1019 :secret (lexical-let ((v (mapcar #'1+ (buffer-string))))
1020 (lambda () (apply #'string (mapcar #'1- v)))))))
1021 (goto-char (point-min))
1022 (let ((entries (auth-source-netrc-parse-entries check max))
1024 (while (setq alist (pop entries))
1025 (push (nreverse alist) result)))
1027 (when (< 0 modified)
1028 (when auth-source-gpg-encrypt-to
1029 ;; (see bug#7487) making `epa-file-encrypt-to' local to
1030 ;; this buffer lets epa-file skip the key selection query
1031 ;; (see the `local-variable-p' check in
1032 ;; `epa-file-write-region').
1033 (unless (local-variable-p 'epa-file-encrypt-to (current-buffer))
1034 (make-local-variable 'epa-file-encrypt-to))
1035 (if (listp auth-source-gpg-encrypt-to)
1036 (setq epa-file-encrypt-to auth-source-gpg-encrypt-to)))
1038 ;; ask AFTER we've successfully opened the file
1039 (when (y-or-n-p (format "Save file %s? (%d deletions)"
1041 (write-region (point-min) (point-max) file nil 'silent)
1042 (auth-source-do-debug
1043 "auth-source-netrc-parse: modified %d lines in %s"
1046 (nreverse result))))))
1048 (defun auth-source-netrc-parse-next-interesting ()
1049 "Advance to the next interesting position in the current buffer."
1050 ;; If we're looking at a comment or are at the end of the line, move forward
1051 (while (or (looking-at "#")
1055 (skip-chars-forward "\t "))
1057 (defun auth-source-netrc-parse-one ()
1058 "Read one thing from the current buffer."
1059 (auth-source-netrc-parse-next-interesting)
1061 (when (or (looking-at "'\\([^']*\\)'")
1062 (looking-at "\"\\([^\"]*\\)\"")
1063 (looking-at "\\([^ \t\n]+\\)"))
1064 (forward-char (length (match-string 0)))
1065 (auth-source-netrc-parse-next-interesting)
1066 (match-string-no-properties 1)))
1068 ;; with thanks to org-mode
1069 (defsubst auth-source-current-line (&optional pos)
1071 (and pos (goto-char pos))
1072 ;; works also in narrowed buffer, because we start at 1, not point-min
1073 (+ (if (bolp) 1 0) (count-lines 1 (point)))))
1075 (defun auth-source-netrc-parse-entries(check max)
1076 "Parse up to MAX netrc entries, passed by CHECK, from the current buffer."
1077 (let ((adder (lambda(check alist all)
1080 (> max (length all))
1081 (funcall check alist))
1084 item item2 all alist default)
1085 (while (setq item (auth-source-netrc-parse-one))
1086 (setq default (equal item "default"))
1087 ;; We're starting a new machine. Save the old one.
1090 (equal item "machine")))
1091 ;; (auth-source-do-trivia
1092 ;; "auth-source-netrc-parse-entries: got entry %S" alist)
1093 (setq all (funcall adder check alist all)
1095 ;; In default entries, we don't have a next token.
1096 ;; We store them as ("machine" . t)
1098 (push (cons "machine" t) alist)
1099 ;; Not a default entry. Grab the next item.
1100 (when (setq item2 (auth-source-netrc-parse-one))
1101 ;; Did we get a "machine" value?
1102 (if (equal item2 "machine")
1105 "%s: Unexpected `machine' token at line %d"
1106 "auth-source-netrc-parse-entries"
1107 (auth-source-current-line))
1109 (push (cons item item2) alist)))))
1111 ;; Clean up: if there's an entry left over, use it.
1113 (setq all (funcall adder check alist all))
1114 ;; (auth-source-do-trivia
1115 ;; "auth-source-netrc-parse-entries: got2 entry %S" alist)
1119 (defvar auth-source-passphrase-alist nil)
1121 (defun auth-source-token-passphrase-callback-function (_context _key-id file)
1122 (let* ((file (file-truename file))
1123 (entry (assoc file auth-source-passphrase-alist))
1125 ;; return the saved passphrase, calling a function if needed
1126 (or (copy-sequence (if (functionp (cdr entry))
1127 (funcall (cdr entry))
1131 (setq entry (list file))
1132 (push entry auth-source-passphrase-alist))
1135 (format "Passphrase for %s tokens: " file)
1137 (setcdr entry (lexical-let ((p (copy-sequence passphrase)))
1141 ;; (auth-source-epa-extract-gpg-token "gpg:LS0tLS1CRUdJTiBQR1AgTUVTU0FHRS0tLS0tClZlcnNpb246IEdudVBHIHYxLjQuMTEgKEdOVS9MaW51eCkKCmpBMEVBd01DT25qMjB1ak9rZnRneVI3K21iNm9aZWhuLzRad3cySkdlbnVaKzRpeEswWDY5di9icDI1U1dsQT0KPS9yc2wKLS0tLS1FTkQgUEdQIE1FU1NBR0UtLS0tLQo=" "~/.netrc")
1142 (defun auth-source-epa-extract-gpg-token (secret file)
1143 "Pass either the decoded SECRET or the gpg:BASE64DATA version.
1144 FILE is the file from which we obtained this token."
1145 (when (string-match "^gpg:\\(.+\\)" secret)
1146 (setq secret (base64-decode-string (match-string 1 secret))))
1147 (let ((context (epg-make-context 'OpenPGP)))
1148 (epg-context-set-passphrase-callback
1150 (cons #'auth-source-token-passphrase-callback-function
1152 (epg-decrypt-string context secret)))
1154 (defvar pp-escape-newlines)
1156 ;; (insert (auth-source-epa-make-gpg-token "mysecret" "~/.netrc"))
1157 (defun auth-source-epa-make-gpg-token (secret file)
1158 (let ((context (epg-make-context 'OpenPGP))
1159 (pp-escape-newlines nil)
1161 (epg-context-set-armor context t)
1162 (epg-context-set-passphrase-callback
1164 (cons #'auth-source-token-passphrase-callback-function
1166 (setq cipher (epg-encrypt-string context secret nil))
1169 (base64-encode-region (point-min) (point-max) t)
1170 (concat "gpg:" (buffer-substring-no-properties
1174 (defun auto-source--symbol-keyword (symbol)
1175 (intern (format ":%s" symbol)))
1177 (defun auth-source-netrc-normalize (alist filename)
1178 (mapcar (lambda (entry)
1180 (while (setq item (pop entry))
1181 (let ((k (car item))
1184 ;; apply key aliases
1185 (setq k (cond ((member k '("machine")) "host")
1186 ((member k '("login" "account")) "user")
1187 ((member k '("protocol")) "port")
1188 ((member k '("password")) "secret")
1191 ;; send back the secret in a function (lexical binding)
1192 (when (equal k "secret")
1193 (setq v (lexical-let ((lexv v)
1194 (token-decoder nil))
1195 (when (string-match "^gpg:" lexv)
1196 ;; it's a GPG token: create a token decoder
1197 ;; which unsets itself once
1201 (auth-source-epa-extract-gpg-token
1204 (setq token-decoder nil)))))
1207 (setq lexv (funcall token-decoder lexv)))
1209 (setq ret (plist-put ret
1210 (auto-source--symbol-keyword k)
1215 ;; (setq secret (plist-get (nth 0 (auth-source-search :host t :type 'netrc :K 1 :max 1)) :secret))
1218 (defun* auth-source-netrc-search (&rest
1220 &key backend require create
1221 type max host user port
1223 "Given a property list SPEC, return search matches from the :backend.
1224 See `auth-source-search' for details on SPEC."
1225 ;; just in case, check that the type is correct (null or same as the backend)
1226 (assert (or (null type) (eq type (oref backend type)))
1227 t "Invalid netrc search: %s %s")
1229 (let ((results (auth-source-netrc-normalize
1230 (auth-source-netrc-parse
1233 :file (oref backend source)
1237 (oref backend source))))
1239 ;; if we need to create an entry AND none were found to match
1243 ;; create based on the spec and record the value
1245 ;; if the user did not want to create the entry
1246 ;; in the file, it will be returned
1247 (apply (slot-value backend 'create-function) spec)
1248 ;; if not, we do the search again without :create
1249 ;; to get the updated data.
1251 ;; the result will be returned, even if the search fails
1252 (apply #'auth-source-netrc-search
1253 (plist-put spec :create nil)))))
1256 (defun auth-source-netrc-element-or-first (v)
1261 ;; (auth-source-search :host "nonesuch" :type 'netrc :max 1 :create t)
1262 ;; (auth-source-search :host "nonesuch" :type 'netrc :max 1 :create t :create-extra-keys '((A "default A") (B)))
1264 (defun* auth-source-netrc-create (&rest spec
1268 (let* ((base-required '(host user port secret))
1269 ;; we know (because of an assertion in auth-source-search) that the
1270 ;; :create parameter is either t or a list (which includes nil)
1271 (create-extra (if (eq t create) nil create))
1272 (current-data (car (auth-source-search :max 1
1275 (required (append base-required create-extra))
1276 (file (oref backend source))
1278 ;; `valist' is an alist
1280 ;; `artificial' will be returned if no creation is needed
1283 ;; only for base required elements (defined as function parameters):
1284 ;; fill in the valist with whatever data we may have from the search
1285 ;; we complete the first value if it's a list and use the value otherwise
1286 (dolist (br base-required)
1287 (let ((val (plist-get spec (auto-source--symbol-keyword br))))
1289 (let ((br-choice (cond
1290 ;; all-accepting choice (predicate is t)
1292 ;; just the value otherwise
1295 (auth-source--aput valist br br-choice))))))
1297 ;; for extra required elements, see if the spec includes a value for them
1298 (dolist (er create-extra)
1299 (let ((k (auto-source--symbol-keyword er))
1300 (keys (loop for i below (length spec) by 2
1301 collect (nth i spec))))
1303 (auth-source--aput valist er (plist-get spec k)))))
1305 ;; for each required element
1306 (dolist (r required)
1307 (let* ((data (auth-source--aget valist r))
1308 ;; take the first element if the data is a list
1309 (data (or (auth-source-netrc-element-or-first data)
1310 (plist-get current-data
1311 (auto-source--symbol-keyword r))))
1312 ;; this is the default to be offered
1313 (given-default (auth-source--aget
1314 auth-source-creation-defaults r))
1315 ;; the default supplementals are simple:
1316 ;; for the user, try `given-default' and then (user-login-name);
1317 ;; otherwise take `given-default'
1319 ((and (not given-default) (eq r 'user))
1322 (printable-defaults (list
1325 (auth-source-netrc-element-or-first
1326 (auth-source--aget valist 'user))
1327 (plist-get artificial :user)
1331 (auth-source-netrc-element-or-first
1332 (auth-source--aget valist 'host))
1333 (plist-get artificial :host)
1337 (auth-source-netrc-element-or-first
1338 (auth-source--aget valist 'port))
1339 (plist-get artificial :port)
1341 (prompt (or (auth-source--aget auth-source-creation-prompts r)
1343 (secret "%p password for %u@%h: ")
1344 (user "%p user name for %h: ")
1345 (host "%p host name for user %u: ")
1346 (port "%p port for %u@%h: "))
1347 (format "Enter %s (%%u@%%h:%%p): " r)))
1348 (prompt (auth-source-format-prompt
1350 `((?u ,(auth-source--aget printable-defaults 'user))
1351 (?h ,(auth-source--aget printable-defaults 'host))
1352 (?p ,(auth-source--aget printable-defaults 'port))))))
1354 ;; Store the data, prompting for the password if needed.
1357 ;; Special case prompt for passwords.
1358 ;; 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)))
1359 ;; TODO: or maybe leave as (setq auth-source-netrc-use-gpg-tokens 'never)
1360 (let* ((ep (format "Use GPG password tokens in %s?" file))
1363 ((eq auth-source-netrc-use-gpg-tokens 'never)
1365 ((listp auth-source-netrc-use-gpg-tokens)
1366 (let ((check (copy-sequence
1367 auth-source-netrc-use-gpg-tokens))
1370 (setq item (pop check))
1371 (when (or (eq (car item) t)
1372 (string-match (car item) file))
1373 (setq ret (cdr item))
1375 ;; FIXME: `ret' unused.
1376 ;; Should we return it here?
1379 (plain (or (eval default) (read-passwd prompt))))
1380 ;; ask if we don't know what to do (in which case
1381 ;; auth-source-netrc-use-gpg-tokens must be a list)
1383 (setq gpg-encrypt (if (y-or-n-p ep) 'gpg 'never))
1384 ;; TODO: save the defcustom now? or ask?
1385 (setq auth-source-netrc-use-gpg-tokens
1386 (cons `(,file ,gpg-encrypt)
1387 auth-source-netrc-use-gpg-tokens)))
1388 (if (eq gpg-encrypt 'gpg)
1389 (auth-source-epa-make-gpg-token plain file)
1391 (if (stringp default)
1392 (read-string (if (string-match ": *\\'" prompt)
1393 (concat (substring prompt 0 (match-beginning 0))
1394 " (default " default "): ")
1395 (concat prompt "(default " default ") "))
1400 (setq artificial (plist-put artificial
1401 (auto-source--symbol-keyword r)
1403 (lexical-let ((data data))
1407 ;; When r is not an empty string...
1408 (when (and (stringp data)
1409 (< 0 (length data)))
1410 ;; this function is not strictly necessary but I think it
1411 ;; makes the code clearer -tzz
1412 (let ((printer (lambda ()
1413 ;; append the key (the symbol name of r)
1414 ;; and the value in r
1417 (if (zerop (length add)) "" " ")
1418 ;; remap auth-source tokens to netrc
1423 (port "port") ; redundant but clearer
1424 (t (symbol-name r)))
1425 (if (string-match "[\"# ]" data)
1428 (setq add (concat add (funcall printer)))))))
1433 (lexical-let ((file file)
1435 (lambda () (auth-source-netrc-saver file add))))
1439 ;;(funcall (plist-get (nth 0 (auth-source-search :host '("nonesuch2") :user "tzz" :port "imap" :create t :max 1)) :save-function))
1440 (defun auth-source-netrc-saver (file add)
1441 "Save a line ADD in FILE, prompting along the way.
1442 Respects `auth-source-save-behavior'. Uses
1443 `auth-source-netrc-cache' to avoid prompting more than once."
1444 (let* ((key (format "%s %s" file (rfc2104-hash 'md5 64 16 file add)))
1445 (cached (assoc key auth-source-netrc-cache)))
1448 (auth-source-do-trivia
1449 "auth-source-netrc-saver: found previous run for key %s, returning"
1452 (when (file-exists-p file)
1453 (insert-file-contents file))
1454 (when auth-source-gpg-encrypt-to
1455 ;; (see bug#7487) making `epa-file-encrypt-to' local to
1456 ;; this buffer lets epa-file skip the key selection query
1457 ;; (see the `local-variable-p' check in
1458 ;; `epa-file-write-region').
1459 (unless (local-variable-p 'epa-file-encrypt-to (current-buffer))
1460 (make-local-variable 'epa-file-encrypt-to))
1461 (if (listp auth-source-gpg-encrypt-to)
1462 (setq epa-file-encrypt-to auth-source-gpg-encrypt-to)))
1463 ;; we want the new data to be found first, so insert at beginning
1464 (goto-char (point-min))
1466 ;; Ask AFTER we've successfully opened the file.
1467 (let ((prompt (format "Save auth info to file %s? " file))
1468 (done (not (eq auth-source-save-behavior 'ask)))
1469 (bufname "*auth-source Help*")
1472 (setq k (auth-source-read-char-choice prompt '(?y ?n ?N ?e ??)))
1476 (with-output-to-temp-buffer bufname
1478 (concat "(y)es, save\n"
1479 "(n)o but use the info\n"
1480 "(N)o and don't ask to save again\n"
1482 "(?) for help as you can see.\n"))
1483 ;; Why? Doesn't with-output-to-temp-buffer already do
1484 ;; the exact same thing anyway? --Stef
1485 (set-buffer standard-output)
1492 (customize-save-variable 'auth-source-save-behavior nil))
1493 (?e (setq add (read-string "Line to add: " add)))
1496 (when (get-buffer-window bufname)
1497 (delete-window (get-buffer-window bufname)))
1499 ;; Make sure the info is not saved.
1500 (when (null auth-source-save-behavior)
1503 (when (< 0 (length add))
1508 (write-region (point-min) (point-max) file nil 'silent)
1509 ;; Make the .authinfo file non-world-readable.
1510 (set-file-modes file #o600)
1511 (auth-source-do-debug
1512 "auth-source-netrc-create: wrote 1 new line to %s"
1514 (message "Saved new authentication information to %s" file)
1516 (auth-source--aput auth-source-netrc-cache key "ran"))))
1518 ;;; Backend specific parsing: Secrets API backend
1520 ;; (let ((auth-sources '(default))) (auth-source-search :max 1 :create t))
1521 ;; (let ((auth-sources '(default))) (auth-source-search :max 1 :delete t))
1522 ;; (let ((auth-sources '(default))) (auth-source-search :max 1))
1523 ;; (let ((auth-sources '(default))) (auth-source-search))
1524 ;; (let ((auth-sources '("secrets:Login"))) (auth-source-search :max 1))
1525 ;; (let ((auth-sources '("secrets:Login"))) (auth-source-search :max 1 :signon_realm "https://git.gnus.org/Git"))
1527 (defun auth-source-secrets-listify-pattern (pattern)
1528 "Convert a pattern with lists to a list of string patterns.
1530 auth-source patterns can have values of the form :foo (\"bar\"
1531 \"qux\"), which means to match any secret with :foo equal to
1532 \"bar\" or :foo equal to \"qux\". The secrets backend supports
1533 only string values for patterns, so this routine returns a list
1534 of patterns that is equivalent to the single original pattern
1535 when interpreted such that if a secret matches any pattern in the
1536 list, it matches the original pattern."
1539 (let* ((key (pop pattern))
1540 (value (pop pattern))
1541 (tails (auth-source-secrets-listify-pattern pattern))
1542 (heads (if (stringp value)
1543 (list (list key value))
1544 (mapcar (lambda (v) (list key v)) value))))
1550 collect (append h tl))))))
1552 (defun* auth-source-secrets-search (&rest
1554 &key backend create delete label max
1556 "Search the Secrets API; spec is like `auth-source'.
1558 The :label key specifies the item's label. It is the only key
1559 that can specify a substring. Any :label value besides a string
1560 will allow any label.
1562 All other search keys must match exactly. If you need substring
1563 matching, do a wider search and narrow it down yourself.
1565 You'll get back all the properties of the token as a plist.
1567 Here's an example that looks for the first item in the `Login'
1570 (let ((auth-sources \\='(\"secrets:Login\")))
1571 (auth-source-search :max 1)
1573 Here's another that looks for the first item in the `Login'
1574 Secrets collection whose label contains `gnus':
1576 (let ((auth-sources \\='(\"secrets:Login\")))
1577 (auth-source-search :max 1 :label \"gnus\")
1579 And this one looks for the first item in the `Login' Secrets
1580 collection that's a Google Chrome entry for the git.gnus.org site
1581 authentication tokens:
1583 (let ((auth-sources \\='(\"secrets:Login\")))
1584 (auth-source-search :max 1 :signon_realm \"https://git.gnus.org/Git\"))
1588 (assert (not create) nil
1589 "The Secrets API auth-source backend doesn't support creation yet")
1591 ;; (secrets-delete-item coll elt)
1592 (assert (not delete) nil
1593 "The Secrets API auth-source backend doesn't support deletion yet")
1595 (let* ((coll (oref backend source))
1596 (max (or max 5000)) ; sanity check: default to stop at 5K
1597 (ignored-keys '(:create :delete :max :backend :label :require :type))
1598 (search-keys (loop for i below (length spec) by 2
1599 unless (memq (nth i spec) ignored-keys)
1600 collect (nth i spec)))
1601 ;; build a search spec without the ignored keys
1602 ;; if a search key is nil or t (match anything), we skip it
1603 (search-specs (auth-source-secrets-listify-pattern
1604 (apply #'append (mapcar
1606 (if (or (null (plist-get spec k))
1607 (eq t (plist-get spec k)))
1609 (list k (plist-get spec k))))
1611 ;; needed keys (always including host, login, port, and secret)
1612 (returned-keys (mm-delete-duplicates (append
1613 '(:host :login :port :secret)
1616 (loop for search-spec in search-specs
1618 (loop for item in (apply #'secrets-search-items coll search-spec)
1619 unless (and (stringp label)
1620 (not (string-match label item)))
1622 ;; TODO: respect max in `secrets-search-items', not after the fact
1623 (items (butlast items (- (length items) max)))
1624 ;; convert the item name to a full plist
1625 (items (mapcar (lambda (item)
1627 ;; make an entry for the secret (password) element
1630 (lexical-let ((v (secrets-get-secret coll item)))
1632 ;; rewrite the entry from ((k1 v1) (k2 v2)) to plist
1634 (mapcar (lambda (entry)
1635 (list (car entry) (cdr entry)))
1636 (secrets-get-attributes coll item)))))
1638 ;; ensure each item has each key in `returned-keys'
1639 (items (mapcar (lambda (plist)
1642 (mapcar (lambda (req)
1643 (if (plist-get plist req)
1651 (defun auth-source-secrets-create (&rest spec)
1653 ;; (apply 'secrets-create-item (auth-get-source entry) name passwd spec)
1656 ;;; Backend specific parsing: Mac OS Keychain (using /usr/bin/security) backend
1658 ;; (let ((auth-sources '(macos-keychain-internet))) (auth-source-search :max 1 :create t))
1659 ;; (let ((auth-sources '(macos-keychain-internet))) (auth-source-search :max 1 :delete t))
1660 ;; (let ((auth-sources '(macos-keychain-internet))) (auth-source-search :max 1))
1661 ;; (let ((auth-sources '(macos-keychain-internet))) (auth-source-search))
1663 ;; (let ((auth-sources '(macos-keychain-generic))) (auth-source-search :max 1 :create t))
1664 ;; (let ((auth-sources '(macos-keychain-generic))) (auth-source-search :max 1 :delete t))
1665 ;; (let ((auth-sources '(macos-keychain-generic))) (auth-source-search :max 1))
1666 ;; (let ((auth-sources '(macos-keychain-generic))) (auth-source-search))
1668 ;; (let ((auth-sources '("macos-keychain-internet:/Users/tzz/Library/Keychains/login.keychain"))) (auth-source-search :max 1))
1669 ;; (let ((auth-sources '("macos-keychain-generic:Login"))) (auth-source-search :max 1 :host "git.gnus.org"))
1670 ;; (let ((auth-sources '("macos-keychain-generic:Login"))) (auth-source-search :max 1))
1672 (defun* auth-source-macos-keychain-search (&rest
1674 &key backend create delete
1677 "Search the MacOS Keychain; spec is like `auth-source'.
1679 All search keys must match exactly. If you need substring
1680 matching, do a wider search and narrow it down yourself.
1682 You'll get back all the properties of the token as a plist.
1684 The :type key is either `macos-keychain-internet' or
1685 `macos-keychain-generic'.
1687 For the internet keychain type, the :label key searches the
1688 item's labels (\"-l LABEL\" passed to \"/usr/bin/security\").
1689 Similarly, :host maps to \"-s HOST\", :user maps to \"-a USER\",
1690 and :port maps to \"-P PORT\" or \"-r PROT\"
1691 \(note PROT has to be a 4-character string).
1693 For the generic keychain type, the :label key searches the item's
1694 labels (\"-l LABEL\" passed to \"/usr/bin/security\").
1695 Similarly, :host maps to \"-c HOST\" (the \"creator\" keychain
1696 field), :user maps to \"-a USER\", and :port maps to \"-s PORT\".
1698 Here's an example that looks for the first item in the default
1699 generic MacOS Keychain:
1701 (let ((auth-sources \\='(macos-keychain-generic)))
1702 (auth-source-search :max 1)
1704 Here's another that looks for the first item in the internet
1705 MacOS Keychain collection whose label is `gnus':
1707 (let ((auth-sources \\='(macos-keychain-internet)))
1708 (auth-source-search :max 1 :label \"gnus\")
1710 And this one looks for the first item in the internet keychain
1711 entries for git.gnus.org:
1713 (let ((auth-sources \\='(macos-keychain-internet\")))
1714 (auth-source-search :max 1 :host \"git.gnus.org\"))
1717 (assert (not create) nil
1718 "The MacOS Keychain auth-source backend doesn't support creation yet")
1720 ;; (macos-keychain-delete-item coll elt)
1721 (assert (not delete) nil
1722 "The MacOS Keychain auth-source backend doesn't support deletion yet")
1724 (let* ((coll (oref backend source))
1725 (max (or max 5000)) ; sanity check: default to stop at 5K
1726 (ignored-keys '(:create :delete :max :backend :label))
1727 (search-keys (loop for i below (length spec) by 2
1728 unless (memq (nth i spec) ignored-keys)
1729 collect (nth i spec)))
1730 ;; build a search spec without the ignored keys
1731 ;; if a search key is nil or t (match anything), we skip it
1732 (search-spec (apply #'append (mapcar
1734 (if (or (null (plist-get spec k))
1735 (eq t (plist-get spec k)))
1737 (list k (plist-get spec k))))
1739 ;; needed keys (always including host, login, port, and secret)
1740 (returned-keys (mm-delete-duplicates (append
1741 '(:host :login :port :secret)
1743 (items (apply #'auth-source-macos-keychain-search-items
1749 ;; ensure each item has each key in `returned-keys'
1750 (items (mapcar (lambda (plist)
1753 (mapcar (lambda (req)
1754 (if (plist-get plist req)
1762 (defun* auth-source-macos-keychain-search-items (coll _type _max
1767 (let* ((keychain-generic (eq type 'macos-keychain-generic))
1768 (args `(,(if keychain-generic
1769 "find-generic-password"
1770 "find-internet-password")
1772 (ret (list :type type)))
1774 (setq args (append args (list "-l" label))))
1776 (setq args (append args (list (if keychain-generic "-c" "-s") host))))
1778 (setq args (append args (list "-a" user))))
1781 (if keychain-generic
1782 (setq args (append args (list "-s" port)))
1783 (setq args (append args (list
1784 (if (string-match "[0-9]+" port) "-P" "-r")
1787 (unless (equal coll "default")
1788 (setq args (append args (list coll))))
1791 (apply #'call-process "/usr/bin/security" nil t nil args)
1792 (goto-char (point-min))
1795 ((looking-at "^password: \"\\(.+\\)\"$")
1796 (setq ret (auth-source-macos-keychain-result-append
1800 (lexical-let ((v (match-string 1)))
1802 ;; TODO: check if this is really the label
1803 ;; match 0x00000007 <blob>="AppleID"
1804 ((looking-at "^[ ]+0x00000007 <blob>=\"\\(.+\\)\"")
1805 (setq ret (auth-source-macos-keychain-result-append
1810 ;; match "crtr"<uint32>="aapl"
1811 ;; match "svce"<blob>="AppleID"
1812 ((looking-at "^[ ]+\"\\([a-z]+\\)\"[^=]+=\"\\(.+\\)\"")
1813 (setq ret (auth-source-macos-keychain-result-append
1817 (match-string 2)))))
1819 ;; return `ret' iff it has the :secret key
1820 (and (plist-get ret :secret) (list ret))))
1822 (defun auth-source-macos-keychain-result-append (result generic k v)
1824 (push (auto-source--symbol-keyword
1826 ((equal k "acct") "user")
1827 ;; for generic keychains, creator is host, service is port
1828 ((and generic (equal k "crtr")) "host")
1829 ((and generic (equal k "svce")) "port")
1830 ;; for internet keychains, protocol is port, server is host
1831 ((and (not generic) (equal k "ptcl")) "port")
1832 ((and (not generic) (equal k "srvr")) "host")
1836 (defun auth-source-macos-keychain-create (&rest spec)
1840 ;;; Backend specific parsing: PLSTORE backend
1842 (defun* auth-source-plstore-search (&rest
1844 &key backend create delete
1847 "Search the PLSTORE; spec is like `auth-source'."
1848 (let* ((store (oref backend data))
1849 (max (or max 5000)) ; sanity check: default to stop at 5K
1850 (ignored-keys '(:create :delete :max :backend :label :require :type))
1851 (search-keys (loop for i below (length spec) by 2
1852 unless (memq (nth i spec) ignored-keys)
1853 collect (nth i spec)))
1854 ;; build a search spec without the ignored keys
1855 ;; if a search key is nil or t (match anything), we skip it
1856 (search-spec (apply #'append (mapcar
1858 (let ((v (plist-get spec k)))
1866 ;; needed keys (always including host, login, port, and secret)
1867 (returned-keys (mm-delete-duplicates (append
1868 '(:host :login :port :secret)
1870 (items (plstore-find store search-spec))
1871 (item-names (mapcar #'car items))
1872 (items (butlast items (- (length items) max)))
1873 ;; convert the item to a full plist
1874 (items (mapcar (lambda (item)
1875 (let* ((plist (copy-tree (cdr item)))
1876 (secret (plist-member plist :secret)))
1880 (lexical-let ((v (car (cdr secret))))
1884 ;; ensure each item has each key in `returned-keys'
1885 (items (mapcar (lambda (plist)
1888 (mapcar (lambda (req)
1889 (if (plist-get plist req)
1896 ;; if we need to create an entry AND none were found to match
1900 ;; create based on the spec and record the value
1902 ;; if the user did not want to create the entry
1903 ;; in the file, it will be returned
1904 (apply (slot-value backend 'create-function) spec)
1905 ;; if not, we do the search again without :create
1906 ;; to get the updated data.
1908 ;; the result will be returned, even if the search fails
1909 (apply #'auth-source-plstore-search
1910 (plist-put spec :create nil)))))
1913 (dolist (item-name item-names)
1914 (plstore-delete store item-name))
1915 (plstore-save store)))
1918 (defun* auth-source-plstore-create (&rest spec
1922 (let* ((base-required '(host user port secret))
1923 (base-secret '(secret))
1924 ;; we know (because of an assertion in auth-source-search) that the
1925 ;; :create parameter is either t or a list (which includes nil)
1926 (create-extra (if (eq t create) nil create))
1927 (current-data (car (auth-source-search :max 1
1930 (required (append base-required create-extra))
1931 ;; `valist' is an alist
1933 ;; `artificial' will be returned if no creation is needed
1937 ;; only for base required elements (defined as function parameters):
1938 ;; fill in the valist with whatever data we may have from the search
1939 ;; we complete the first value if it's a list and use the value otherwise
1940 (dolist (br base-required)
1941 (let ((val (plist-get spec (auto-source--symbol-keyword br))))
1943 (let ((br-choice (cond
1944 ;; all-accepting choice (predicate is t)
1946 ;; just the value otherwise
1949 (auth-source--aput valist br br-choice))))))
1951 ;; for extra required elements, see if the spec includes a value for them
1952 (dolist (er create-extra)
1953 (let ((k (auto-source--symbol-keyword er))
1954 (keys (loop for i below (length spec) by 2
1955 collect (nth i spec))))
1957 (auth-source--aput valist er (plist-get spec k)))))
1959 ;; for each required element
1960 (dolist (r required)
1961 (let* ((data (auth-source--aget valist r))
1962 ;; take the first element if the data is a list
1963 (data (or (auth-source-netrc-element-or-first data)
1964 (plist-get current-data
1965 (auto-source--symbol-keyword r))))
1966 ;; this is the default to be offered
1967 (given-default (auth-source--aget
1968 auth-source-creation-defaults r))
1969 ;; the default supplementals are simple:
1970 ;; for the user, try `given-default' and then (user-login-name);
1971 ;; otherwise take `given-default'
1973 ((and (not given-default) (eq r 'user))
1976 (printable-defaults (list
1979 (auth-source-netrc-element-or-first
1980 (auth-source--aget valist 'user))
1981 (plist-get artificial :user)
1985 (auth-source-netrc-element-or-first
1986 (auth-source--aget valist 'host))
1987 (plist-get artificial :host)
1991 (auth-source-netrc-element-or-first
1992 (auth-source--aget valist 'port))
1993 (plist-get artificial :port)
1995 (prompt (or (auth-source--aget auth-source-creation-prompts r)
1997 (secret "%p password for %u@%h: ")
1998 (user "%p user name for %h: ")
1999 (host "%p host name for user %u: ")
2000 (port "%p port for %u@%h: "))
2001 (format "Enter %s (%%u@%%h:%%p): " r)))
2002 (prompt (auth-source-format-prompt
2004 `((?u ,(auth-source--aget printable-defaults 'user))
2005 (?h ,(auth-source--aget printable-defaults 'host))
2006 (?p ,(auth-source--aget printable-defaults 'port))))))
2008 ;; Store the data, prompting for the password if needed.
2011 (or (eval default) (read-passwd prompt))
2012 (if (stringp default)
2014 (if (string-match ": *\\'" prompt)
2015 (concat (substring prompt 0 (match-beginning 0))
2016 " (default " default "): ")
2017 (concat prompt "(default " default ") "))
2022 (if (member r base-secret)
2023 (setq secret-artificial
2024 (plist-put secret-artificial
2025 (auto-source--symbol-keyword r)
2027 (setq artificial (plist-put artificial
2028 (auto-source--symbol-keyword r)
2030 (plstore-put (oref backend data)
2031 (sha1 (format "%s@%s:%s"
2032 (plist-get artificial :user)
2033 (plist-get artificial :host)
2034 (plist-get artificial :port)))
2035 artificial secret-artificial)
2036 (if (y-or-n-p (format "Save auth info to file %s? "
2037 (plstore-get-file (oref backend data))))
2038 (plstore-save (oref backend data)))))
2042 ;; (auth-source-user-or-password '("login" "password") "imap.myhost.com" t "tzz")
2044 ;; deprecate the old interface
2045 (make-obsolete 'auth-source-user-or-password
2046 'auth-source-search "Emacs 24.1")
2047 (make-obsolete 'auth-source-forget-user-or-password
2048 'auth-source-forget "Emacs 24.1")
2050 (defun auth-source-user-or-password
2051 (mode host port &optional username create-missing delete-existing)
2052 "Find MODE (string or list of strings) matching HOST and PORT.
2054 DEPRECATED in favor of `auth-source-search'!
2056 USERNAME is optional and will be used as \"login\" in a search
2057 across the Secret Service API (see secrets.el) if the resulting
2058 items don't have a username. This means that if you search for
2059 username \"joe\" and it matches an item but the item doesn't have
2060 a :user attribute, the username \"joe\" will be returned.
2062 A non nil DELETE-EXISTING means deleting any matching password
2063 entry in the respective sources. This is useful only when
2064 CREATE-MISSING is non nil as well; the intended use case is to
2065 remove wrong password entries.
2067 If no matching entry is found, and CREATE-MISSING is non nil,
2068 the password will be retrieved interactively, and it will be
2069 stored in the password database which matches best (see
2072 MODE can be \"login\" or \"password\"."
2073 (auth-source-do-debug
2074 "auth-source-user-or-password: DEPRECATED get %s for %s (%s) + user=%s"
2075 mode host port username)
2077 (let* ((listy (listp mode))
2078 (mode (if listy mode (list mode)))
2079 ;; (cname (if username
2080 ;; (format "%s %s:%s %s" mode host port username)
2081 ;; (format "%s %s:%s" mode host port)))
2082 (search (list :host host :port port))
2083 (search (if username (append search (list :user username)) search))
2084 (search (if create-missing
2085 (append search (list :create t))
2087 (search (if delete-existing
2088 (append search (list :delete t))
2090 ;; (found (if (not delete-existing)
2091 ;; (gethash cname auth-source-cache)
2092 ;; (remhash cname auth-source-cache)
2097 (auth-source-do-debug
2098 "auth-source-user-or-password: DEPRECATED cached %s=%s for %s (%s) + %s"
2100 ;; don't show the password
2101 (if (and (member "password" mode) t)
2105 found) ; return the found data
2106 ;; else, if not found, search with a max of 1
2107 (let ((choice (nth 0 (apply #'auth-source-search
2108 (append '(:max 1) search)))))
2112 ((equal "password" m)
2113 (push (if (plist-get choice :secret)
2114 (funcall (plist-get choice :secret))
2117 (push (plist-get choice :user) found)))))
2118 (setq found (nreverse found))
2119 (setq found (if listy found (car-safe found)))))
2123 (defun auth-source-user-and-password (host &optional user)
2124 (let* ((auth-info (car
2128 :user "yourusername"
2130 :require '(:user :secret)
2135 :require '(:user :secret)
2137 (user (plist-get auth-info :user))
2138 (password (plist-get auth-info :secret)))
2139 (when (functionp password)
2140 (setq password (funcall password)))
2141 (list user password auth-info)))
2143 (provide 'auth-source)
2145 ;;; auth-source.el ends here