1 ;;; auth-source.el --- authentication sources for Gnus and Emacs
3 ;; Copyright (C) 2008-2011 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))
49 (autoload 'secrets-create-item "secrets")
50 (autoload 'secrets-delete-item "secrets")
51 (autoload 'secrets-get-alias "secrets")
52 (autoload 'secrets-get-attributes "secrets")
53 (autoload 'secrets-get-secret "secrets")
54 (autoload 'secrets-list-collections "secrets")
55 (autoload 'secrets-search-items "secrets")
57 (defvar secrets-enabled)
59 (defgroup auth-source nil
60 "Authentication sources."
61 :version "23.1" ;; No Gnus
65 (defcustom auth-source-cache-expiry 7200
66 "How many seconds passwords are cached, or nil to disable
67 expiring. Overrides `password-cache-expiry' through a
70 :type '(choice (const :tag "Never" nil)
71 (const :tag "All Day" 86400)
72 (const :tag "2 Hours" 7200)
73 (const :tag "30 Minutes" 1800)
74 (integer :tag "Seconds")))
76 (defclass auth-source-backend ()
81 :documentation "The backend type.")
82 (source :initarg :source
85 :documentation "The backend source.")
90 :documentation "The backend host.")
95 :documentation "The backend user.")
100 :documentation "The backend protocol.")
101 (create-function :initarg :create-function
105 :documentation "The create function.")
106 (search-function :initarg :search-function
110 :documentation "The search function.")))
112 (defcustom auth-source-protocols '((imap "imap" "imaps" "143" "993")
113 (pop3 "pop3" "pop" "pop3s" "110" "995")
117 "List of authentication protocols and their names"
120 :version "23.2" ;; No Gnus
121 :type '(repeat :tag "Authentication Protocols"
122 (cons :tag "Protocol Entry"
123 (symbol :tag "Protocol")
125 (string :tag "Name")))))
127 ;;; generate all the protocols in a format Customize can use
128 ;;; TODO: generate on the fly from auth-source-protocols
129 (defconst auth-source-protocols-customize
131 (let ((p (car-safe a)))
133 :tag (upcase (symbol-name p))
135 auth-source-protocols))
137 (defvar auth-source-creation-defaults nil
138 "Defaults for creating token values. Usually let-bound.")
140 (defvar auth-source-creation-prompts nil
141 "Default prompts for token values. Usually let-bound.")
143 (make-obsolete 'auth-source-hide-passwords nil "Emacs 24.1")
145 (defcustom auth-source-save-behavior 'ask
146 "If set, auth-source will respect it for save behavior."
148 :version "23.2" ;; No Gnus
150 :tag "auth-source new token save behavior"
151 (const :tag "Always save" t)
152 (const :tag "Never save" nil)
153 (const :tag "Ask" ask)))
155 (defvar auth-source-magic "auth-source-magic ")
157 (defcustom auth-source-do-cache t
158 "Whether auth-source should cache information with `password-cache'."
160 :version "23.2" ;; No Gnus
163 (defcustom auth-source-debug nil
164 "Whether auth-source should log debug messages.
166 If the value is nil, debug messages are not logged.
168 If the value is t, debug messages are logged with `message'. In
169 that case, your authentication data will be in the clear (except
172 If the value is a function, debug messages are logged by calling
173 that function using the same arguments as `message'."
175 :version "23.2" ;; No Gnus
177 :tag "auth-source debugging mode"
178 (const :tag "Log using `message' to the *Messages* buffer" t)
179 (const :tag "Log all trivia with `message' to the *Messages* buffer"
181 (function :tag "Function that takes arguments like `message'")
182 (const :tag "Don't log anything" nil)))
184 (defcustom auth-sources '("~/.authinfo.gpg" "~/.authinfo" "~/.netrc")
185 "List of authentication sources.
187 The default will get login and password information from
188 \"~/.authinfo.gpg\", which you should set up with the EPA/EPG
189 packages to be encrypted. If that file doesn't exist, it will
190 try the unencrypted version \"~/.authinfo\" and the famous
193 See the auth.info manual for details.
195 Each entry is the authentication type with optional properties.
197 It's best to customize this with `M-x customize-variable' because the choices
198 can get pretty complex."
200 :version "24.1" ;; No Gnus
201 :type `(repeat :tag "Authentication Sources"
203 (string :tag "Just a file")
204 (const :tag "Default Secrets API Collection" 'default)
205 (const :tag "Login Secrets API Collection" "secrets:Login")
206 (const :tag "Temp Secrets API Collection" "secrets:session")
207 (list :tag "Source definition"
208 (const :format "" :value :source)
209 (choice :tag "Authentication backend choice"
210 (string :tag "Authentication Source (file)")
212 :tag "Secret Service API/KWallet/GNOME Keyring"
213 (const :format "" :value :secrets)
214 (choice :tag "Collection to use"
215 (string :tag "Collection name")
216 (const :tag "Default" 'default)
217 (const :tag "Login" "Login")
219 :tag "Temporary" "session"))))
220 (repeat :tag "Extra Parameters" :inline t
221 (choice :tag "Extra parameter"
224 (const :format "" :value :host)
225 (choice :tag "Host (machine) choice"
228 :tag "Regular expression")))
231 (const :format "" :value :port)
235 ,@auth-source-protocols-customize))
236 (list :tag "User" :inline t
237 (const :format "" :value :user)
238 (choice :tag "Personality/Username"
240 (string :tag "Name")))))))))
242 (defcustom auth-source-gpg-encrypt-to t
243 "List of recipient keys that `authinfo.gpg' encrypted to.
244 If the value is not a list, symmetric encryption will be used."
246 :version "24.1" ;; No Gnus
247 :type '(choice (const :tag "Symmetric encryption" t)
248 (repeat :tag "Recipient public keys"
249 (string :tag "Recipient public key"))))
251 ;; temp for debugging
252 ;; (unintern 'auth-source-protocols)
253 ;; (unintern 'auth-sources)
254 ;; (customize-variable 'auth-sources)
255 ;; (setq auth-sources nil)
256 ;; (format "%S" auth-sources)
257 ;; (customize-variable 'auth-source-protocols)
258 ;; (setq auth-source-protocols nil)
259 ;; (format "%S" auth-source-protocols)
260 ;; (auth-source-pick nil :host "a" :port 'imap)
261 ;; (auth-source-user-or-password "login" "imap.myhost.com" 'imap)
262 ;; (auth-source-user-or-password "password" "imap.myhost.com" 'imap)
263 ;; (auth-source-user-or-password-imap "login" "imap.myhost.com")
264 ;; (auth-source-user-or-password-imap "password" "imap.myhost.com")
265 ;; (auth-source-protocol-defaults 'imap)
267 ;; (let ((auth-source-debug 'debug)) (auth-source-do-debug "hello"))
268 ;; (let ((auth-source-debug t)) (auth-source-do-debug "hello"))
269 ;; (let ((auth-source-debug nil)) (auth-source-do-debug "hello"))
270 (defun auth-source-do-debug (&rest msg)
271 (when auth-source-debug
272 (apply 'auth-source-do-warn msg)))
274 (defun auth-source-do-trivia (&rest msg)
275 (when (or (eq auth-source-debug 'trivia)
276 (functionp auth-source-debug))
277 (apply 'auth-source-do-warn msg)))
279 (defun auth-source-do-warn (&rest msg)
281 ;; set logger to either the function in auth-source-debug or 'message
282 ;; note that it will be 'message if auth-source-debug is nil
283 (if (functionp auth-source-debug)
289 ;;; (auth-source-read-char-choice "enter choice? " '(?a ?b ?q))
290 (defun auth-source-read-char-choice (prompt choices)
291 "Read one of CHOICES by `read-char-choice', or `read-char'.
292 `dropdown-list' support is disabled because it doesn't work reliably.
293 Only one of CHOICES will be returned. The PROMPT is augmented
294 with \"[a/b/c] \" if CHOICES is '\(?a ?b ?c\)."
296 (let* ((prompt-choices
297 (apply 'concat (loop for c in choices
298 collect (format "%c/" c))))
299 (prompt-choices (concat "[" (substring prompt-choices 0 -1) "] "))
300 (full-prompt (concat prompt prompt-choices))
303 (while (not (memq k choices))
305 ((fboundp 'read-char-choice)
306 (read-char-choice full-prompt choices))
307 (t (message "%s" full-prompt)
308 (setq k (read-char))))))
311 ;; (auth-source-pick nil :host "any" :port 'imap :user "joe")
312 ;; (auth-source-pick t :host "any" :port 'imap :user "joe")
313 ;; (setq auth-sources '((:source (:secrets default) :host t :port t :user "joe")
314 ;; (:source (:secrets "session") :host t :port t :user "joe")
315 ;; (:source (:secrets "Login") :host t :port t)
316 ;; (:source "~/.authinfo.gpg" :host t :port t)))
318 ;; (setq auth-sources '((:source (:secrets default) :host t :port t :user "joe")
319 ;; (:source (:secrets "session") :host t :port t :user "joe")
320 ;; (:source (:secrets "Login") :host t :port t)
323 ;; (setq auth-sources '((:source "~/.authinfo.gpg" :host t :port t)))
325 ;; (auth-source-backend-parse "myfile.gpg")
326 ;; (auth-source-backend-parse 'default)
327 ;; (auth-source-backend-parse "secrets:Login")
329 (defun auth-source-backend-parse (entry)
330 "Creates an auth-source-backend from an ENTRY in `auth-sources'."
331 (auth-source-backend-parse-parameters
334 ;; take 'default and recurse to get it as a Secrets API default collection
335 ;; matching any user, host, and protocol
337 (auth-source-backend-parse '(:source (:secrets default))))
338 ;; take secrets:XYZ and recurse to get it as Secrets API collection "XYZ"
339 ;; matching any user, host, and protocol
340 ((and (stringp entry) (string-match "^secrets:\\(.+\\)" entry))
341 (auth-source-backend-parse `(:source (:secrets ,(match-string 1 entry)))))
342 ;; take just a file name and recurse to get it as a netrc file
343 ;; matching any user, host, and protocol
345 (auth-source-backend-parse `(:source ,entry)))
347 ;; a file name with parameters
348 ((stringp (plist-get entry :source))
350 (plist-get entry :source)
351 :source (plist-get entry :source)
353 :search-function 'auth-source-netrc-search
354 :create-function 'auth-source-netrc-create))
356 ;; the Secrets API. We require the package, in order to have a
357 ;; defined value for `secrets-enabled'.
359 (not (null (plist-get entry :source))) ; the source must not be nil
360 (listp (plist-get entry :source)) ; and it must be a list
361 (require 'secrets nil t) ; and we must load the Secrets API
362 secrets-enabled) ; and that API must be enabled
364 ;; the source is either the :secrets key in ENTRY or
365 ;; if that's missing or nil, it's "session"
366 (let ((source (or (plist-get (plist-get entry :source) :secrets)
369 ;; if the source is a symbol, we look for the alias named so,
370 ;; and if that alias is missing, we use "Login"
371 (when (symbolp source)
372 (setq source (or (secrets-get-alias (symbol-name source))
375 (if (featurep 'secrets)
377 (format "Secrets API (%s)" source)
380 :search-function 'auth-source-secrets-search
381 :create-function 'auth-source-secrets-create)
383 "auth-source-backend-parse: no Secrets API, ignoring spec: %S" entry)
385 (format "Ignored Secrets API (%s)" source)
392 "auth-source-backend-parse: invalid backend spec: %S" entry)
398 (defun auth-source-backend-parse-parameters (entry backend)
399 "Fills in the extra auth-source-backend parameters of ENTRY.
400 Using the plist ENTRY, get the :host, :port, and :user search
402 (let ((entry (if (stringp entry)
406 (when (setq val (plist-get entry :host))
407 (oset backend host val))
408 (when (setq val (plist-get entry :user))
409 (oset backend user val))
410 (when (setq val (plist-get entry :port))
411 (oset backend port val)))
414 ;; (mapcar 'auth-source-backend-parse auth-sources)
416 (defun* auth-source-search (&rest spec
417 &key type max host user port secret
418 require create delete
420 "Search or modify authentication backends according to SPEC.
422 This function parses `auth-sources' for matches of the SPEC
423 plist. It can optionally create or update an authentication
424 token if requested. A token is just a standard Emacs property
425 list with a :secret property that can be a function; all the
426 other properties will always hold scalar values.
428 Typically the :secret property, if present, contains a password.
430 Common search keys are :max, :host, :port, and :user. In
431 addition, :create specifies how tokens will be or created.
432 Finally, :type can specify which backend types you want to check.
434 A string value is always matched literally. A symbol is matched
435 as its string value, literally. All the SPEC values can be
436 single values (symbol or string) or lists thereof (in which case
437 any of the search terms matches).
439 :create t means to create a token if possible.
441 A new token will be created if no matching tokens were found.
442 The new token will have only the keys the backend requires. For
443 the netrc backend, for instance, that's the user, host, and
448 \(let ((auth-source-creation-defaults '((user . \"defaultUser\")
449 (A . \"default A\"))))
450 (auth-source-search :host \"mine\" :type 'netrc :max 1
451 :P \"pppp\" :Q \"qqqq\"
456 \"Search for any entry matching host 'mine' in backends of type
457 'netrc', maximum one result.
459 Create a new entry if you found none. The netrc backend will
460 automatically require host, user, and port. The host will be
461 'mine'. We prompt for the user with default 'defaultUser' and
462 for the port without a default. We will not prompt for A, Q,
463 or P. The resulting token will only have keys user, host, and
466 :create '(A B C) also means to create a token if possible.
468 The behavior is like :create t but if the list contains any
469 parameter, that parameter will be required in the resulting
470 token. The value for that parameter will be obtained from the
471 search parameters or from user input. If any queries are needed,
472 the alist `auth-source-creation-defaults' will be checked for the
473 default value. If the user, host, or port are missing, the alist
474 `auth-source-creation-prompts' will be used to look up the
475 prompts IN THAT ORDER (so the 'user prompt will be queried first,
476 then 'host, then 'port, and finally 'secret). Each prompt string
477 can use %u, %h, and %p to show the user, host, and port.
481 \(let ((auth-source-creation-defaults '((user . \"defaultUser\")
482 (A . \"default A\")))
483 (auth-source-creation-prompts
484 '((password . \"Enter IMAP password for %h:%p: \"))))
485 (auth-source-search :host '(\"nonesuch\" \"twosuch\") :type 'netrc :max 1
486 :P \"pppp\" :Q \"qqqq\"
491 \"Search for any entry matching host 'nonesuch'
492 or 'twosuch' in backends of type 'netrc', maximum one result.
494 Create a new entry if you found none. The netrc backend will
495 automatically require host, user, and port. The host will be
496 'nonesuch' and Q will be 'qqqq'. We prompt for the password
497 with the shown prompt. We will not prompt for Q. The resulting
498 token will have keys user, host, port, A, B, and Q. It will not
499 have P with any value, even though P is used in the search to
500 find only entries that have P set to 'pppp'.\"
502 When multiple values are specified in the search parameter, the
503 user is prompted for which one. So :host (X Y Z) would ask the
504 user to choose between X, Y, and Z.
506 This creation can fail if the search was not specific enough to
507 create a new token (it's up to the backend to decide that). You
508 should `catch' the backend-specific error as usual. Some
509 backends (netrc, at least) will prompt the user rather than throw
512 :require (A B C) means that only results that contain those
513 tokens will be returned. Thus for instance requiring :secret
514 will ensure that any results will actually have a :secret
517 :delete t means to delete any found entries. nil by default.
518 Use `auth-source-delete' in ELisp code instead of calling
519 `auth-source-search' directly with this parameter.
521 :type (X Y Z) will check only those backend types. 'netrc and
522 'secrets are the only ones supported right now.
524 :max N means to try to return at most N items (defaults to 1).
525 When 0 the function will return just t or nil to indicate if any
526 matches were found. More than N items may be returned, depending
527 on the search and the backend.
529 :host (X Y Z) means to match only hosts X, Y, or Z according to
530 the match rules above. Defaults to t.
532 :user (X Y Z) means to match only users X, Y, or Z according to
533 the match rules above. Defaults to t.
535 :port (P Q R) means to match only protocols P, Q, or R.
538 :K (V1 V2 V3) for any other key K will match values V1, V2, or
539 V3 (note the match rules above).
541 The return value is a list with at most :max tokens. Each token
542 is a plist with keys :backend :host :port :user, plus any other
543 keys provided by the backend (notably :secret). But note the
544 exception for :max 0, which see above.
546 The token can hold a :save-function key. If you call that, the
547 user will be prompted to save the data to the backend. You can't
548 request that this should happen right after creation, because
549 `auth-source-search' has no way of knowing if the token is
550 actually useful. So the caller must arrange to call this function.
552 The token's :secret key can hold a function. In that case you
553 must call it to obtain the actual value."
554 (let* ((backends (mapcar 'auth-source-backend-parse auth-sources))
556 (ignored-keys '(:require :create :delete :max))
557 (keys (loop for i below (length spec) by 2
558 unless (memq (nth i spec) ignored-keys)
559 collect (nth i spec)))
560 (cached (auth-source-remembered-p spec))
561 ;; note that we may have cached results but found is still nil
562 ;; (there were no results from the search)
563 (found (auth-source-recall spec))
564 filtered-backends accessor-key backend)
566 (if (and cached auth-source-do-cache)
567 (auth-source-do-debug
568 "auth-source-search: found %d CACHED results matching %S"
572 (or (eq t create) (listp create)) t
573 "Invalid auth-source :create parameter (must be t or a list): %s %s")
577 "Invalid auth-source :require parameter (must be a list): %s")
579 (setq filtered-backends (copy-sequence backends))
580 (dolist (backend backends)
582 ;; ignore invalid slots
583 (condition-case signal
584 (unless (eval `(auth-source-search-collection
586 (oref backend ,key)))
587 (setq filtered-backends (delq backend filtered-backends))
589 (invalid-slot-name))))
591 (auth-source-do-trivia
592 "auth-source-search: found %d backends matching %S"
593 (length filtered-backends) spec)
595 ;; (debug spec "filtered" filtered-backends)
596 ;; First go through all the backends without :create, so we can
598 (setq found (auth-source-search-backends filtered-backends
602 ;; create is always nil here
606 (auth-source-do-debug
607 "auth-source-search: found %d results (max %d) matching %S"
608 (length found) max spec)
610 ;; If we didn't find anything, then we allow the backend(s) to
611 ;; create the entries.
614 (setq found (auth-source-search-backends filtered-backends
620 (auth-source-do-debug
621 "auth-source-search: CREATED %d results (max %d) matching %S"
622 (length found) max spec))
624 ;; note we remember the lack of result too, if it's applicable
625 (when auth-source-do-cache
626 (auth-source-remember spec found)))
630 (defun auth-source-search-backends (backends spec max create delete require)
632 (dolist (backend backends)
633 (when (> max (length matches)) ; when we need more matches...
634 (let* ((bmatches (apply
635 (slot-value backend 'search-function)
637 ;; note we're overriding whatever the spec
638 ;; has for :require, :create, and :delete
644 (auth-source-do-trivia
645 "auth-source-search-backend: got %d (max %d) in %s:%s matching %S"
646 (length bmatches) max
647 (slot-value backend :type)
648 (slot-value backend :source)
650 (setq matches (append matches bmatches))))))
653 ;;; (auth-source-search :max 1)
654 ;;; (funcall (plist-get (nth 0 (auth-source-search :max 1)) :secret))
655 ;;; (auth-source-search :host "nonesuch" :type 'netrc :K 1)
656 ;;; (auth-source-search :host "nonesuch" :type 'secrets)
658 (defun* auth-source-delete (&rest spec
661 "Delete entries from the authentication backends according to SPEC.
662 Calls `auth-source-search' with the :delete property in SPEC set to t.
663 The backend may not actually delete the entries.
665 Returns the deleted entries."
666 (auth-source-search (plist-put spec :delete t)))
668 (defun auth-source-search-collection (collection value)
669 "Returns t is VALUE is t or COLLECTION is t or contains VALUE."
670 (when (and (atom collection) (not (eq t collection)))
671 (setq collection (list collection)))
673 ;; (debug :collection collection :value value)
674 (or (eq collection t)
676 (equal collection value)
677 (member value collection)))
679 (defun auth-source-forget-all-cached ()
680 "Forget all cached auth-source data."
682 (loop for sym being the symbols of password-data
683 ;; when the symbol name starts with auth-source-magic
684 when (string-match (concat "^" auth-source-magic)
687 do (password-cache-remove (symbol-name sym))))
689 (defun auth-source-remember (spec found)
690 "Remember FOUND search results for SPEC."
691 (let ((password-cache-expiry auth-source-cache-expiry))
693 (concat auth-source-magic (format "%S" spec)) found)))
695 (defun auth-source-recall (spec)
696 "Recall FOUND search results for SPEC."
697 (password-read-from-cache
698 (concat auth-source-magic (format "%S" spec))))
700 (defun auth-source-remembered-p (spec)
701 "Check if SPEC is remembered."
703 (concat auth-source-magic (format "%S" spec))))
705 (defun auth-source-forget (spec)
706 "Forget any cached data matching SPEC exactly.
708 This is the same SPEC you passed to `auth-source-search'.
709 Returns t or nil for forgotten or not found."
710 (password-cache-remove (concat auth-source-magic (format "%S" spec))))
712 ;;; (loop for sym being the symbols of password-data when (string-match (concat "^" auth-source-magic) (symbol-name sym)) collect (symbol-name sym))
714 ;;; (auth-source-remember '(:host "wedd") '(4 5 6))
715 ;;; (auth-source-remembered-p '(:host "wedd"))
716 ;;; (auth-source-remember '(:host "xedd") '(1 2 3))
717 ;;; (auth-source-remembered-p '(:host "xedd"))
718 ;;; (auth-source-remembered-p '(:host "zedd"))
719 ;;; (auth-source-recall '(:host "xedd"))
720 ;;; (auth-source-recall '(:host t))
721 ;;; (auth-source-forget+ :host t)
723 (defun* auth-source-forget+ (&rest spec &allow-other-keys)
724 "Forget any cached data matching SPEC. Returns forgotten count.
726 This is not a full `auth-source-search' spec but works similarly.
727 For instance, \(:host \"myhost\" \"yourhost\") would find all the
728 cached data that was found with a search for those two hosts,
729 while \(:host t) would find all host entries."
732 (loop for sym being the symbols of password-data
733 ;; when the symbol name matches with auth-source-magic
734 when (and (setq sname (symbol-name sym))
735 (string-match (concat "^" auth-source-magic "\\(.+\\)")
737 ;; and the spec matches what was stored in the cache
738 (auth-source-specmatchp spec (read (match-string 1 sname))))
741 (password-cache-remove sname)
745 (defun auth-source-specmatchp (spec stored)
746 (let ((keys (loop for i below (length spec) by 2
747 collect (nth i spec))))
750 (unless (auth-source-search-collection (plist-get stored key)
751 (plist-get spec key))
755 ;;; (auth-source-pick-first-password :host "z.lifelogs.com")
756 ;;; (auth-source-pick-first-password :port "imap")
757 (defun auth-source-pick-first-password (&rest spec)
758 "Pick the first secret found from applying SPEC to `auth-source-search'."
759 (let* ((result (nth 0 (apply 'auth-source-search (plist-put spec :max 1))))
760 (secret (plist-get result :secret)))
762 (if (functionp secret)
766 ;; (auth-source-format-prompt "test %u %h %p" '((?u "user") (?h "host")))
767 (defun auth-source-format-prompt (prompt alist)
768 "Format PROMPT using %x (for any character x) specifiers in ALIST."
770 (let ((c (nth 0 cell))
773 (setq prompt (replace-regexp-in-string (format "%%%c" c) v prompt)))))
776 (defun auth-source-ensure-strings (values)
777 (unless (listp values)
778 (setq values (list values)))
779 (mapcar (lambda (value)
785 ;;; Backend specific parsing: netrc/authinfo backend
787 (defvar auth-source-netrc-cache nil)
789 ;;; (auth-source-netrc-parse "~/.authinfo.gpg")
790 (defun* auth-source-netrc-parse (&rest
792 &key file max host user port delete require
794 "Parse FILE and return a list of all entries in the file.
795 Note that the MAX parameter is used so we can exit the parse early."
797 ;; We got already parsed contents; just return it.
799 (when (file-exists-p file)
800 (setq port (auth-source-ensure-strings port))
802 (let* ((tokens '("machine" "host" "default" "login" "user"
803 "password" "account" "macdef" "force"
805 (max (or max 5000)) ; sanity check: default to stop at 5K
807 (cached (cdr-safe (assoc file auth-source-netrc-cache)))
808 (cached-mtime (plist-get cached :mtime))
809 (cached-secrets (plist-get cached :secret))
810 alist elem result pair)
812 (if (and (functionp cached-secrets)
814 (nth 5 (file-attributes file))))
816 (auth-source-do-trivia
817 "auth-source-netrc-parse: using CACHED file data for %s"
819 (insert (funcall cached-secrets)))
820 (insert-file-contents file)
821 ;; cache all netrc files (used to be just .gpg files)
822 ;; Store the contents of the file heavily encrypted in memory.
823 ;; (note for the irony-impaired: they are just obfuscated)
824 (aput 'auth-source-netrc-cache file
825 (list :mtime (nth 5 (file-attributes file))
826 :secret (lexical-let ((v (rot13-string
827 (base64-encode-string
829 (lambda () (base64-decode-string
830 (rot13-string v)))))))
831 (goto-char (point-min))
832 ;; Go through the file, line by line.
833 (while (and (not (eobp))
836 (narrow-to-region (point) (point-at-eol))
837 ;; For each line, get the tokens and values.
839 (skip-chars-forward "\t ")
840 ;; Skip lines that begin with a "#".
841 (if (eq (char-after) ?#)
842 (goto-char (point-max))
845 (if (= (following-char) ?\")
846 (read (current-buffer))
848 (point) (progn (skip-chars-forward "^\t ")
851 ((equal elem "macdef")
852 ;; We skip past the macro definition.
854 (while (and (zerop (forward-line 1))
856 (narrow-to-region (point) (point)))
857 ((member elem tokens)
858 ;; Tokens that don't have a following value are ignored,
860 (when (and pair (or (cdr pair)
861 (equal (car pair) "default")))
863 (setq pair (list elem)))
865 ;; Values that haven't got a preceding token are ignored.
869 (setq pair nil)))))))
873 (auth-source-search-collection
876 (aget alist "machine")
879 (auth-source-search-collection
883 (aget alist "account")
886 (auth-source-search-collection
890 (aget alist "protocol")
893 ;; the required list of keys is nil, or
895 ;; every element of require is in the normalized list
896 (let ((normalized (nth 0 (auth-source-netrc-normalize
898 (loop for req in require
899 always (plist-get normalized req)))))
901 (push (nreverse alist) result)
902 ;; to delete a line, we just comment it out
904 (goto-char (point-min))
913 (when auth-source-gpg-encrypt-to
914 ;; (see bug#7487) making `epa-file-encrypt-to' local to
915 ;; this buffer lets epa-file skip the key selection query
916 ;; (see the `local-variable-p' check in
917 ;; `epa-file-write-region').
918 (unless (local-variable-p 'epa-file-encrypt-to (current-buffer))
919 (make-local-variable 'epa-file-encrypt-to))
920 (if (listp auth-source-gpg-encrypt-to)
921 (setq epa-file-encrypt-to auth-source-gpg-encrypt-to)))
923 ;; ask AFTER we've successfully opened the file
924 (when (y-or-n-p (format "Save file %s? (%d deletions)"
926 (write-region (point-min) (point-max) file nil 'silent)
927 (auth-source-do-debug
928 "auth-source-netrc-parse: modified %d lines in %s"
931 (nreverse result))))))
933 (defun auth-source-netrc-normalize (alist)
934 (mapcar (lambda (entry)
936 (while (setq item (pop entry))
941 (setq k (cond ((member k '("machine")) "host")
942 ((member k '("login" "account")) "user")
943 ((member k '("protocol")) "port")
944 ((member k '("password")) "secret")
947 ;; send back the secret in a function (lexical binding)
948 (when (equal k "secret")
949 (setq v (lexical-let ((v v))
952 (setq ret (plist-put ret
953 (intern (concat ":" k))
959 ;;; (setq secret (plist-get (nth 0 (auth-source-search :host t :type 'netrc :K 1 :max 1)) :secret))
962 (defun* auth-source-netrc-search (&rest
964 &key backend require create delete
965 type max host user port
967 "Given a property list SPEC, return search matches from the :backend.
968 See `auth-source-search' for details on SPEC."
969 ;; just in case, check that the type is correct (null or same as the backend)
970 (assert (or (null type) (eq type (oref backend type)))
971 t "Invalid netrc search: %s %s")
973 (let ((results (auth-source-netrc-normalize
974 (auth-source-netrc-parse
978 :file (oref backend source)
981 :port (or port t)))))
983 ;; if we need to create an entry AND none were found to match
987 ;; create based on the spec and record the value
989 ;; if the user did not want to create the entry
990 ;; in the file, it will be returned
991 (apply (slot-value backend 'create-function) spec)
992 ;; if not, we do the search again without :create
993 ;; to get the updated data.
995 ;; the result will be returned, even if the search fails
996 (apply 'auth-source-netrc-search
997 (plist-put spec :create nil)))))
1000 (defun auth-source-netrc-element-or-first (v)
1005 ;;; (auth-source-search :host "nonesuch" :type 'netrc :max 1 :create t)
1006 ;;; (auth-source-search :host "nonesuch" :type 'netrc :max 1 :create t :create-extra-keys '((A "default A") (B)))
1008 (defun* auth-source-netrc-create (&rest spec
1010 secret host user port create
1012 (let* ((base-required '(host user port secret))
1013 ;; we know (because of an assertion in auth-source-search) that the
1014 ;; :create parameter is either t or a list (which includes nil)
1015 (create-extra (if (eq t create) nil create))
1016 (required (append base-required create-extra))
1017 (file (oref backend source))
1019 ;; `valist' is an alist
1021 ;; `artificial' will be returned if no creation is needed
1024 ;; only for base required elements (defined as function parameters):
1025 ;; fill in the valist with whatever data we may have from the search
1026 ;; we complete the first value if it's a list and use the value otherwise
1027 (dolist (br base-required)
1028 (when (symbol-value br)
1029 (let ((br-choice (cond
1030 ;; all-accepting choice (predicate is t)
1031 ((eq t (symbol-value br)) nil)
1032 ;; just the value otherwise
1033 (t (symbol-value br)))))
1035 (aput 'valist br br-choice)))))
1037 ;; for extra required elements, see if the spec includes a value for them
1038 (dolist (er create-extra)
1039 (let ((name (concat ":" (symbol-name er)))
1040 (keys (loop for i below (length spec) by 2
1041 collect (nth i spec))))
1043 (when (equal (symbol-name k) name)
1044 (aput 'valist er (plist-get spec k))))))
1046 ;; for each required element
1047 (dolist (r required)
1048 (let* ((data (aget valist r))
1049 ;; take the first element if the data is a list
1050 (data (auth-source-netrc-element-or-first data))
1051 ;; this is the default to be offered
1052 (given-default (aget auth-source-creation-defaults r))
1053 ;; the default supplementals are simple:
1054 ;; for the user, try `given-default' and then (user-login-name);
1055 ;; otherwise take `given-default'
1057 ((and (not given-default) (eq r 'user))
1060 (printable-defaults (list
1063 (auth-source-netrc-element-or-first
1064 (aget valist 'user))
1065 (plist-get artificial :user)
1069 (auth-source-netrc-element-or-first
1070 (aget valist 'host))
1071 (plist-get artificial :host)
1075 (auth-source-netrc-element-or-first
1076 (aget valist 'port))
1077 (plist-get artificial :port)
1079 (prompt (or (aget auth-source-creation-prompts r)
1081 (secret "%p password for %u@%h: ")
1082 (user "%p user name for %h: ")
1083 (host "%p host name for user %u: ")
1084 (port "%p port for %u@%h: "))
1085 (format "Enter %s (%%u@%%h:%%p): " r)))
1086 (prompt (auth-source-format-prompt
1088 `((?u ,(aget printable-defaults 'user))
1089 (?h ,(aget printable-defaults 'host))
1090 (?p ,(aget printable-defaults 'port))))))
1092 ;; store the data, prompting for the password if needed
1095 ((and (null data) (eq r 'secret))
1096 ;; special case prompt for passwords
1097 (read-passwd prompt))
1099 (read-string prompt default))
1100 (t (or data default))))
1103 (setq artificial (plist-put artificial
1104 (intern (concat ":" (symbol-name r)))
1106 (lexical-let ((data data))
1110 ;; when r is not an empty string...
1111 (when (and (stringp data)
1112 (< 0 (length data)))
1113 ;; this function is not strictly necessary but I think it
1114 ;; makes the code clearer -tzz
1115 (let ((printer (lambda ()
1116 ;; append the key (the symbol name of r)
1117 ;; and the value in r
1120 (if (zerop (length add)) "" " ")
1121 ;; remap auth-source tokens to netrc
1125 ('secret "password")
1126 ('port "port") ; redundant but clearer
1127 (t (symbol-name r)))
1128 ;; the value will be printed in %S format
1130 (setq add (concat add (funcall printer)))))))
1135 (lexical-let ((file file)
1137 (lambda () (auth-source-netrc-saver file add))))
1141 ;;(funcall (plist-get (nth 0 (auth-source-search :host '("nonesuch") :user "tzz" :port "imap" :create t :max 1)) :save-function))
1142 (defun auth-source-netrc-saver (file add)
1143 "Save a line ADD in FILE, prompting along the way.
1144 Respects `auth-source-save-behavior'."
1146 (when (file-exists-p file)
1147 (insert-file-contents file))
1148 (when auth-source-gpg-encrypt-to
1149 ;; (see bug#7487) making `epa-file-encrypt-to' local to
1150 ;; this buffer lets epa-file skip the key selection query
1151 ;; (see the `local-variable-p' check in
1152 ;; `epa-file-write-region').
1153 (unless (local-variable-p 'epa-file-encrypt-to (current-buffer))
1154 (make-local-variable 'epa-file-encrypt-to))
1155 (if (listp auth-source-gpg-encrypt-to)
1156 (setq epa-file-encrypt-to auth-source-gpg-encrypt-to)))
1157 ;; we want the new data to be found first, so insert at beginning
1158 (goto-char (point-min))
1160 ;; ask AFTER we've successfully opened the file
1161 (let ((prompt (format "Save auth info to file %s? " file))
1162 (done (not (eq auth-source-save-behavior 'ask)))
1163 (bufname "*auth-source Help*")
1166 (setq k (auth-source-read-char-choice prompt '(?y ?n ?N ?e ??)))
1170 (with-output-to-temp-buffer bufname
1172 (concat "(y)es, save\n"
1173 "(n)o but use the info\n"
1174 "(N)o and don't ask to save again\n"
1176 "(?) for help as you can see.\n"))
1177 (set-buffer standard-output)
1183 auth-source-save-behavior nil))
1184 (?e (setq add (read-string "Line to add: " add)))
1187 (when (get-buffer-window bufname)
1188 (delete-window (get-buffer-window bufname)))
1190 ;; make sure the info is not saved
1191 (when (null auth-source-save-behavior)
1194 (when (< 0 (length add))
1199 (write-region (point-min) (point-max) file nil 'silent)
1200 (auth-source-do-debug
1201 "auth-source-netrc-create: wrote 1 new line to %s"
1203 (message "Saved new authentication information to %s" file)
1206 ;;; Backend specific parsing: Secrets API backend
1208 ;;; (let ((auth-sources '(default))) (auth-source-search :max 1 :create t))
1209 ;;; (let ((auth-sources '(default))) (auth-source-search :max 1 :delete t))
1210 ;;; (let ((auth-sources '(default))) (auth-source-search :max 1))
1211 ;;; (let ((auth-sources '(default))) (auth-source-search))
1212 ;;; (let ((auth-sources '("secrets:Login"))) (auth-source-search :max 1))
1213 ;;; (let ((auth-sources '("secrets:Login"))) (auth-source-search :max 1 :signon_realm "https://git.gnus.org/Git"))
1215 (defun* auth-source-secrets-search (&rest
1217 &key backend create delete label
1218 type max host user port
1220 "Search the Secrets API; spec is like `auth-source'.
1222 The :label key specifies the item's label. It is the only key
1223 that can specify a substring. Any :label value besides a string
1224 will allow any label.
1226 All other search keys must match exactly. If you need substring
1227 matching, do a wider search and narrow it down yourself.
1229 You'll get back all the properties of the token as a plist.
1231 Here's an example that looks for the first item in the 'Login'
1234 \(let ((auth-sources '(\"secrets:Login\")))
1235 (auth-source-search :max 1)
1237 Here's another that looks for the first item in the 'Login'
1238 Secrets collection whose label contains 'gnus':
1240 \(let ((auth-sources '(\"secrets:Login\")))
1241 (auth-source-search :max 1 :label \"gnus\")
1243 And this one looks for the first item in the 'Login' Secrets
1244 collection that's a Google Chrome entry for the git.gnus.org site
1245 authentication tokens:
1247 \(let ((auth-sources '(\"secrets:Login\")))
1248 (auth-source-search :max 1 :signon_realm \"https://git.gnus.org/Git\"))
1252 (assert (not create) nil
1253 "The Secrets API auth-source backend doesn't support creation yet")
1255 ;; (secrets-delete-item coll elt)
1256 (assert (not delete) nil
1257 "The Secrets API auth-source backend doesn't support deletion yet")
1259 (let* ((coll (oref backend source))
1260 (max (or max 5000)) ; sanity check: default to stop at 5K
1261 (ignored-keys '(:create :delete :max :backend :label))
1262 (search-keys (loop for i below (length spec) by 2
1263 unless (memq (nth i spec) ignored-keys)
1264 collect (nth i spec)))
1265 ;; build a search spec without the ignored keys
1266 ;; if a search key is nil or t (match anything), we skip it
1267 (search-spec (apply 'append (mapcar
1269 (if (or (null (plist-get spec k))
1270 (eq t (plist-get spec k)))
1272 (list k (plist-get spec k))))
1274 ;; needed keys (always including host, login, port, and secret)
1275 (returned-keys (mm-delete-duplicates (append
1276 '(:host :login :port :secret)
1278 (items (loop for item in (apply 'secrets-search-items coll search-spec)
1279 unless (and (stringp label)
1280 (not (string-match label item)))
1282 ;; TODO: respect max in `secrets-search-items', not after the fact
1283 (items (butlast items (- (length items) max)))
1284 ;; convert the item name to a full plist
1285 (items (mapcar (lambda (item)
1287 ;; make an entry for the secret (password) element
1290 (lexical-let ((v (secrets-get-secret coll item)))
1292 ;; rewrite the entry from ((k1 v1) (k2 v2)) to plist
1294 (mapcar (lambda (entry)
1295 (list (car entry) (cdr entry)))
1296 (secrets-get-attributes coll item)))))
1298 ;; ensure each item has each key in `returned-keys'
1299 (items (mapcar (lambda (plist)
1302 (mapcar (lambda (req)
1303 (if (plist-get plist req)
1311 (defun* auth-source-secrets-create (&rest
1313 &key backend type max host user port
1316 ;; (apply 'secrets-create-item (auth-get-source entry) name passwd spec)
1321 ;;; (auth-source-user-or-password '("login" "password") "imap.myhost.com" t "tzz")
1323 ;; deprecate the old interface
1324 (make-obsolete 'auth-source-user-or-password
1325 'auth-source-search "Emacs 24.1")
1326 (make-obsolete 'auth-source-forget-user-or-password
1327 'auth-source-forget "Emacs 24.1")
1329 (defun auth-source-user-or-password
1330 (mode host port &optional username create-missing delete-existing)
1331 "Find MODE (string or list of strings) matching HOST and PORT.
1333 DEPRECATED in favor of `auth-source-search'!
1335 USERNAME is optional and will be used as \"login\" in a search
1336 across the Secret Service API (see secrets.el) if the resulting
1337 items don't have a username. This means that if you search for
1338 username \"joe\" and it matches an item but the item doesn't have
1339 a :user attribute, the username \"joe\" will be returned.
1341 A non nil DELETE-EXISTING means deleting any matching password
1342 entry in the respective sources. This is useful only when
1343 CREATE-MISSING is non nil as well; the intended use case is to
1344 remove wrong password entries.
1346 If no matching entry is found, and CREATE-MISSING is non nil,
1347 the password will be retrieved interactively, and it will be
1348 stored in the password database which matches best (see
1351 MODE can be \"login\" or \"password\"."
1352 (auth-source-do-debug
1353 "auth-source-user-or-password: DEPRECATED get %s for %s (%s) + user=%s"
1354 mode host port username)
1356 (let* ((listy (listp mode))
1357 (mode (if listy mode (list mode)))
1359 (format "%s %s:%s %s" mode host port username)
1360 (format "%s %s:%s" mode host port)))
1361 (search (list :host host :port port))
1362 (search (if username (append search (list :user username)) search))
1363 (search (if create-missing
1364 (append search (list :create t))
1366 (search (if delete-existing
1367 (append search (list :delete t))
1369 ;; (found (if (not delete-existing)
1370 ;; (gethash cname auth-source-cache)
1371 ;; (remhash cname auth-source-cache)
1376 (auth-source-do-debug
1377 "auth-source-user-or-password: DEPRECATED cached %s=%s for %s (%s) + %s"
1379 ;; don't show the password
1380 (if (and (member "password" mode) t)
1384 found) ; return the found data
1385 ;; else, if not found, search with a max of 1
1386 (let ((choice (nth 0 (apply 'auth-source-search
1387 (append '(:max 1) search)))))
1391 ((equal "password" m)
1392 (push (if (plist-get choice :secret)
1393 (funcall (plist-get choice :secret))
1396 (push (plist-get choice :user) found)))))
1397 (setq found (nreverse found))
1398 (setq found (if listy found (car-safe found)))))
1402 (provide 'auth-source)
1404 ;;; auth-source.el ends here