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 (autoload 'rfc2104-hash "rfc2104")
59 (defvar secrets-enabled)
61 (defgroup auth-source nil
62 "Authentication sources."
63 :version "23.1" ;; No Gnus
67 (defcustom auth-source-cache-expiry 7200
68 "How many seconds passwords are cached, or nil to disable
69 expiring. Overrides `password-cache-expiry' through a
72 :type '(choice (const :tag "Never" nil)
73 (const :tag "All Day" 86400)
74 (const :tag "2 Hours" 7200)
75 (const :tag "30 Minutes" 1800)
76 (integer :tag "Seconds")))
78 (defclass auth-source-backend ()
83 :documentation "The backend type.")
84 (source :initarg :source
87 :documentation "The backend source.")
92 :documentation "The backend host.")
97 :documentation "The backend user.")
102 :documentation "The backend protocol.")
103 (create-function :initarg :create-function
107 :documentation "The create function.")
108 (search-function :initarg :search-function
112 :documentation "The search function.")))
114 (defcustom auth-source-protocols '((imap "imap" "imaps" "143" "993")
115 (pop3 "pop3" "pop" "pop3s" "110" "995")
119 "List of authentication protocols and their names"
122 :version "23.2" ;; No Gnus
123 :type '(repeat :tag "Authentication Protocols"
124 (cons :tag "Protocol Entry"
125 (symbol :tag "Protocol")
127 (string :tag "Name")))))
129 ;;; generate all the protocols in a format Customize can use
130 ;;; TODO: generate on the fly from auth-source-protocols
131 (defconst auth-source-protocols-customize
133 (let ((p (car-safe a)))
135 :tag (upcase (symbol-name p))
137 auth-source-protocols))
139 (defvar auth-source-creation-defaults nil
140 "Defaults for creating token values. Usually let-bound.")
142 (defvar auth-source-creation-prompts nil
143 "Default prompts for token values. Usually let-bound.")
145 (make-obsolete 'auth-source-hide-passwords nil "Emacs 24.1")
147 (defcustom auth-source-save-behavior 'ask
148 "If set, auth-source will respect it for save behavior."
150 :version "23.2" ;; No Gnus
152 :tag "auth-source new token save behavior"
153 (const :tag "Always save" t)
154 (const :tag "Never save" nil)
155 (const :tag "Ask" ask)))
157 (defvar auth-source-magic "auth-source-magic ")
159 (defcustom auth-source-do-cache t
160 "Whether auth-source should cache information with `password-cache'."
162 :version "23.2" ;; No Gnus
165 (defcustom auth-source-debug nil
166 "Whether auth-source should log debug messages.
168 If the value is nil, debug messages are not logged.
170 If the value is t, debug messages are logged with `message'. In
171 that case, your authentication data will be in the clear (except
174 If the value is a function, debug messages are logged by calling
175 that function using the same arguments as `message'."
177 :version "23.2" ;; No Gnus
179 :tag "auth-source debugging mode"
180 (const :tag "Log using `message' to the *Messages* buffer" t)
181 (const :tag "Log all trivia with `message' to the *Messages* buffer"
183 (function :tag "Function that takes arguments like `message'")
184 (const :tag "Don't log anything" nil)))
186 (defcustom auth-sources '("~/.authinfo.gpg" "~/.authinfo" "~/.netrc")
187 "List of authentication sources.
189 The default will get login and password information from
190 \"~/.authinfo.gpg\", which you should set up with the EPA/EPG
191 packages to be encrypted. If that file doesn't exist, it will
192 try the unencrypted version \"~/.authinfo\" and the famous
195 See the auth.info manual for details.
197 Each entry is the authentication type with optional properties.
199 It's best to customize this with `M-x customize-variable' because the choices
200 can get pretty complex."
202 :version "24.1" ;; No Gnus
203 :type `(repeat :tag "Authentication Sources"
205 (string :tag "Just a file")
206 (const :tag "Default Secrets API Collection" 'default)
207 (const :tag "Login Secrets API Collection" "secrets:Login")
208 (const :tag "Temp Secrets API Collection" "secrets:session")
209 (list :tag "Source definition"
210 (const :format "" :value :source)
211 (choice :tag "Authentication backend choice"
212 (string :tag "Authentication Source (file)")
214 :tag "Secret Service API/KWallet/GNOME Keyring"
215 (const :format "" :value :secrets)
216 (choice :tag "Collection to use"
217 (string :tag "Collection name")
218 (const :tag "Default" 'default)
219 (const :tag "Login" "Login")
221 :tag "Temporary" "session"))))
222 (repeat :tag "Extra Parameters" :inline t
223 (choice :tag "Extra parameter"
226 (const :format "" :value :host)
227 (choice :tag "Host (machine) choice"
230 :tag "Regular expression")))
233 (const :format "" :value :port)
237 ,@auth-source-protocols-customize))
238 (list :tag "User" :inline t
239 (const :format "" :value :user)
240 (choice :tag "Personality/Username"
242 (string :tag "Name")))))))))
244 (defcustom auth-source-gpg-encrypt-to t
245 "List of recipient keys that `authinfo.gpg' encrypted to.
246 If the value is not a list, symmetric encryption will be used."
248 :version "24.1" ;; No Gnus
249 :type '(choice (const :tag "Symmetric encryption" t)
250 (repeat :tag "Recipient public keys"
251 (string :tag "Recipient public key"))))
253 ;; temp for debugging
254 ;; (unintern 'auth-source-protocols)
255 ;; (unintern 'auth-sources)
256 ;; (customize-variable 'auth-sources)
257 ;; (setq auth-sources nil)
258 ;; (format "%S" auth-sources)
259 ;; (customize-variable 'auth-source-protocols)
260 ;; (setq auth-source-protocols nil)
261 ;; (format "%S" auth-source-protocols)
262 ;; (auth-source-pick nil :host "a" :port 'imap)
263 ;; (auth-source-user-or-password "login" "imap.myhost.com" 'imap)
264 ;; (auth-source-user-or-password "password" "imap.myhost.com" 'imap)
265 ;; (auth-source-user-or-password-imap "login" "imap.myhost.com")
266 ;; (auth-source-user-or-password-imap "password" "imap.myhost.com")
267 ;; (auth-source-protocol-defaults 'imap)
269 ;; (let ((auth-source-debug 'debug)) (auth-source-do-debug "hello"))
270 ;; (let ((auth-source-debug t)) (auth-source-do-debug "hello"))
271 ;; (let ((auth-source-debug nil)) (auth-source-do-debug "hello"))
272 (defun auth-source-do-debug (&rest msg)
273 (when auth-source-debug
274 (apply 'auth-source-do-warn msg)))
276 (defun auth-source-do-trivia (&rest msg)
277 (when (or (eq auth-source-debug 'trivia)
278 (functionp auth-source-debug))
279 (apply 'auth-source-do-warn msg)))
281 (defun auth-source-do-warn (&rest msg)
283 ;; set logger to either the function in auth-source-debug or 'message
284 ;; note that it will be 'message if auth-source-debug is nil
285 (if (functionp auth-source-debug)
291 ;;; (auth-source-read-char-choice "enter choice? " '(?a ?b ?q))
292 (defun auth-source-read-char-choice (prompt choices)
293 "Read one of CHOICES by `read-char-choice', or `read-char'.
294 `dropdown-list' support is disabled because it doesn't work reliably.
295 Only one of CHOICES will be returned. The PROMPT is augmented
296 with \"[a/b/c] \" if CHOICES is '\(?a ?b ?c\)."
298 (let* ((prompt-choices
299 (apply 'concat (loop for c in choices
300 collect (format "%c/" c))))
301 (prompt-choices (concat "[" (substring prompt-choices 0 -1) "] "))
302 (full-prompt (concat prompt prompt-choices))
305 (while (not (memq k choices))
307 ((fboundp 'read-char-choice)
308 (read-char-choice full-prompt choices))
309 (t (message "%s" full-prompt)
310 (setq k (read-char))))))
313 ;; (auth-source-pick nil :host "any" :port 'imap :user "joe")
314 ;; (auth-source-pick t :host "any" :port 'imap :user "joe")
315 ;; (setq auth-sources '((:source (:secrets default) :host t :port t :user "joe")
316 ;; (:source (:secrets "session") :host t :port t :user "joe")
317 ;; (:source (:secrets "Login") :host t :port t)
318 ;; (:source "~/.authinfo.gpg" :host t :port t)))
320 ;; (setq auth-sources '((:source (:secrets default) :host t :port t :user "joe")
321 ;; (:source (:secrets "session") :host t :port t :user "joe")
322 ;; (:source (:secrets "Login") :host t :port t)
325 ;; (setq auth-sources '((:source "~/.authinfo.gpg" :host t :port t)))
327 ;; (auth-source-backend-parse "myfile.gpg")
328 ;; (auth-source-backend-parse 'default)
329 ;; (auth-source-backend-parse "secrets:Login")
331 (defun auth-source-backend-parse (entry)
332 "Creates an auth-source-backend from an ENTRY in `auth-sources'."
333 (auth-source-backend-parse-parameters
336 ;; take 'default and recurse to get it as a Secrets API default collection
337 ;; matching any user, host, and protocol
339 (auth-source-backend-parse '(:source (:secrets default))))
340 ;; take secrets:XYZ and recurse to get it as Secrets API collection "XYZ"
341 ;; matching any user, host, and protocol
342 ((and (stringp entry) (string-match "^secrets:\\(.+\\)" entry))
343 (auth-source-backend-parse `(:source (:secrets ,(match-string 1 entry)))))
344 ;; take just a file name and recurse to get it as a netrc file
345 ;; matching any user, host, and protocol
347 (auth-source-backend-parse `(:source ,entry)))
349 ;; a file name with parameters
350 ((stringp (plist-get entry :source))
352 (plist-get entry :source)
353 :source (plist-get entry :source)
355 :search-function 'auth-source-netrc-search
356 :create-function 'auth-source-netrc-create))
358 ;; the Secrets API. We require the package, in order to have a
359 ;; defined value for `secrets-enabled'.
361 (not (null (plist-get entry :source))) ; the source must not be nil
362 (listp (plist-get entry :source)) ; and it must be a list
363 (require 'secrets nil t) ; and we must load the Secrets API
364 secrets-enabled) ; and that API must be enabled
366 ;; the source is either the :secrets key in ENTRY or
367 ;; if that's missing or nil, it's "session"
368 (let ((source (or (plist-get (plist-get entry :source) :secrets)
371 ;; if the source is a symbol, we look for the alias named so,
372 ;; and if that alias is missing, we use "Login"
373 (when (symbolp source)
374 (setq source (or (secrets-get-alias (symbol-name source))
377 (if (featurep 'secrets)
379 (format "Secrets API (%s)" source)
382 :search-function 'auth-source-secrets-search
383 :create-function 'auth-source-secrets-create)
385 "auth-source-backend-parse: no Secrets API, ignoring spec: %S" entry)
387 (format "Ignored Secrets API (%s)" source)
394 "auth-source-backend-parse: invalid backend spec: %S" entry)
400 (defun auth-source-backend-parse-parameters (entry backend)
401 "Fills in the extra auth-source-backend parameters of ENTRY.
402 Using the plist ENTRY, get the :host, :port, and :user search
404 (let ((entry (if (stringp entry)
408 (when (setq val (plist-get entry :host))
409 (oset backend host val))
410 (when (setq val (plist-get entry :user))
411 (oset backend user val))
412 (when (setq val (plist-get entry :port))
413 (oset backend port val)))
416 ;; (mapcar 'auth-source-backend-parse auth-sources)
418 (defun* auth-source-search (&rest spec
419 &key type max host user port secret
420 require create delete
422 "Search or modify authentication backends according to SPEC.
424 This function parses `auth-sources' for matches of the SPEC
425 plist. It can optionally create or update an authentication
426 token if requested. A token is just a standard Emacs property
427 list with a :secret property that can be a function; all the
428 other properties will always hold scalar values.
430 Typically the :secret property, if present, contains a password.
432 Common search keys are :max, :host, :port, and :user. In
433 addition, :create specifies how tokens will be or created.
434 Finally, :type can specify which backend types you want to check.
436 A string value is always matched literally. A symbol is matched
437 as its string value, literally. All the SPEC values can be
438 single values (symbol or string) or lists thereof (in which case
439 any of the search terms matches).
441 :create t means to create a token if possible.
443 A new token will be created if no matching tokens were found.
444 The new token will have only the keys the backend requires. For
445 the netrc backend, for instance, that's the user, host, and
450 \(let ((auth-source-creation-defaults '((user . \"defaultUser\")
451 (A . \"default A\"))))
452 (auth-source-search :host \"mine\" :type 'netrc :max 1
453 :P \"pppp\" :Q \"qqqq\"
458 \"Search for any entry matching host 'mine' in backends of type
459 'netrc', maximum one result.
461 Create a new entry if you found none. The netrc backend will
462 automatically require host, user, and port. The host will be
463 'mine'. We prompt for the user with default 'defaultUser' and
464 for the port without a default. We will not prompt for A, Q,
465 or P. The resulting token will only have keys user, host, and
468 :create '(A B C) also means to create a token if possible.
470 The behavior is like :create t but if the list contains any
471 parameter, that parameter will be required in the resulting
472 token. The value for that parameter will be obtained from the
473 search parameters or from user input. If any queries are needed,
474 the alist `auth-source-creation-defaults' will be checked for the
475 default value. If the user, host, or port are missing, the alist
476 `auth-source-creation-prompts' will be used to look up the
477 prompts IN THAT ORDER (so the 'user prompt will be queried first,
478 then 'host, then 'port, and finally 'secret). Each prompt string
479 can use %u, %h, and %p to show the user, host, and port.
483 \(let ((auth-source-creation-defaults '((user . \"defaultUser\")
484 (A . \"default A\")))
485 (auth-source-creation-prompts
486 '((password . \"Enter IMAP password for %h:%p: \"))))
487 (auth-source-search :host '(\"nonesuch\" \"twosuch\") :type 'netrc :max 1
488 :P \"pppp\" :Q \"qqqq\"
493 \"Search for any entry matching host 'nonesuch'
494 or 'twosuch' in backends of type 'netrc', maximum one result.
496 Create a new entry if you found none. The netrc backend will
497 automatically require host, user, and port. The host will be
498 'nonesuch' and Q will be 'qqqq'. We prompt for the password
499 with the shown prompt. We will not prompt for Q. The resulting
500 token will have keys user, host, port, A, B, and Q. It will not
501 have P with any value, even though P is used in the search to
502 find only entries that have P set to 'pppp'.\"
504 When multiple values are specified in the search parameter, the
505 user is prompted for which one. So :host (X Y Z) would ask the
506 user to choose between X, Y, and Z.
508 This creation can fail if the search was not specific enough to
509 create a new token (it's up to the backend to decide that). You
510 should `catch' the backend-specific error as usual. Some
511 backends (netrc, at least) will prompt the user rather than throw
514 :require (A B C) means that only results that contain those
515 tokens will be returned. Thus for instance requiring :secret
516 will ensure that any results will actually have a :secret
519 :delete t means to delete any found entries. nil by default.
520 Use `auth-source-delete' in ELisp code instead of calling
521 `auth-source-search' directly with this parameter.
523 :type (X Y Z) will check only those backend types. 'netrc and
524 'secrets are the only ones supported right now.
526 :max N means to try to return at most N items (defaults to 1).
527 When 0 the function will return just t or nil to indicate if any
528 matches were found. More than N items may be returned, depending
529 on the search and the backend.
531 :host (X Y Z) means to match only hosts X, Y, or Z according to
532 the match rules above. Defaults to t.
534 :user (X Y Z) means to match only users X, Y, or Z according to
535 the match rules above. Defaults to t.
537 :port (P Q R) means to match only protocols P, Q, or R.
540 :K (V1 V2 V3) for any other key K will match values V1, V2, or
541 V3 (note the match rules above).
543 The return value is a list with at most :max tokens. Each token
544 is a plist with keys :backend :host :port :user, plus any other
545 keys provided by the backend (notably :secret). But note the
546 exception for :max 0, which see above.
548 The token can hold a :save-function key. If you call that, the
549 user will be prompted to save the data to the backend. You can't
550 request that this should happen right after creation, because
551 `auth-source-search' has no way of knowing if the token is
552 actually useful. So the caller must arrange to call this function.
554 The token's :secret key can hold a function. In that case you
555 must call it to obtain the actual value."
556 (let* ((backends (mapcar 'auth-source-backend-parse auth-sources))
558 (ignored-keys '(:require :create :delete :max))
559 (keys (loop for i below (length spec) by 2
560 unless (memq (nth i spec) ignored-keys)
561 collect (nth i spec)))
562 (cached (auth-source-remembered-p spec))
563 ;; note that we may have cached results but found is still nil
564 ;; (there were no results from the search)
565 (found (auth-source-recall spec))
566 filtered-backends accessor-key backend)
568 (if (and cached auth-source-do-cache)
569 (auth-source-do-debug
570 "auth-source-search: found %d CACHED results matching %S"
574 (or (eq t create) (listp create)) t
575 "Invalid auth-source :create parameter (must be t or a list): %s %s")
579 "Invalid auth-source :require parameter (must be a list): %s")
581 (setq filtered-backends (copy-sequence backends))
582 (dolist (backend backends)
584 ;; ignore invalid slots
585 (condition-case signal
586 (unless (eval `(auth-source-search-collection
588 (oref backend ,key)))
589 (setq filtered-backends (delq backend filtered-backends))
591 (invalid-slot-name))))
593 (auth-source-do-trivia
594 "auth-source-search: found %d backends matching %S"
595 (length filtered-backends) spec)
597 ;; (debug spec "filtered" filtered-backends)
598 ;; First go through all the backends without :create, so we can
600 (setq found (auth-source-search-backends filtered-backends
604 ;; create is always nil here
608 (auth-source-do-debug
609 "auth-source-search: found %d results (max %d) matching %S"
610 (length found) max spec)
612 ;; If we didn't find anything, then we allow the backend(s) to
613 ;; create the entries.
616 (setq found (auth-source-search-backends filtered-backends
622 (auth-source-do-debug
623 "auth-source-search: CREATED %d results (max %d) matching %S"
624 (length found) max spec))
626 ;; note we remember the lack of result too, if it's applicable
627 (when auth-source-do-cache
628 (auth-source-remember spec found)))
632 (defun auth-source-search-backends (backends spec max create delete require)
634 (dolist (backend backends)
635 (when (> max (length matches)) ; when we need more matches...
636 (let* ((bmatches (apply
637 (slot-value backend 'search-function)
639 ;; note we're overriding whatever the spec
640 ;; has for :require, :create, and :delete
646 (auth-source-do-trivia
647 "auth-source-search-backend: got %d (max %d) in %s:%s matching %S"
648 (length bmatches) max
649 (slot-value backend :type)
650 (slot-value backend :source)
652 (setq matches (append matches bmatches))))))
655 ;;; (auth-source-search :max 1)
656 ;;; (funcall (plist-get (nth 0 (auth-source-search :max 1)) :secret))
657 ;;; (auth-source-search :host "nonesuch" :type 'netrc :K 1)
658 ;;; (auth-source-search :host "nonesuch" :type 'secrets)
660 (defun* auth-source-delete (&rest spec
663 "Delete entries from the authentication backends according to SPEC.
664 Calls `auth-source-search' with the :delete property in SPEC set to t.
665 The backend may not actually delete the entries.
667 Returns the deleted entries."
668 (auth-source-search (plist-put spec :delete t)))
670 (defun auth-source-search-collection (collection value)
671 "Returns t is VALUE is t or COLLECTION is t or contains VALUE."
672 (when (and (atom collection) (not (eq t collection)))
673 (setq collection (list collection)))
675 ;; (debug :collection collection :value value)
676 (or (eq collection t)
678 (equal collection value)
679 (member value collection)))
681 (defun auth-source-forget-all-cached ()
682 "Forget all cached auth-source data."
684 (loop for sym being the symbols of password-data
685 ;; when the symbol name starts with auth-source-magic
686 when (string-match (concat "^" auth-source-magic)
689 do (password-cache-remove (symbol-name sym))))
691 (defun auth-source-remember (spec found)
692 "Remember FOUND search results for SPEC."
693 (let ((password-cache-expiry auth-source-cache-expiry))
695 (concat auth-source-magic (format "%S" spec)) found)))
697 (defun auth-source-recall (spec)
698 "Recall FOUND search results for SPEC."
699 (password-read-from-cache
700 (concat auth-source-magic (format "%S" spec))))
702 (defun auth-source-remembered-p (spec)
703 "Check if SPEC is remembered."
705 (concat auth-source-magic (format "%S" spec))))
707 (defun auth-source-forget (spec)
708 "Forget any cached data matching SPEC exactly.
710 This is the same SPEC you passed to `auth-source-search'.
711 Returns t or nil for forgotten or not found."
712 (password-cache-remove (concat auth-source-magic (format "%S" spec))))
714 ;;; (loop for sym being the symbols of password-data when (string-match (concat "^" auth-source-magic) (symbol-name sym)) collect (symbol-name sym))
716 ;;; (auth-source-remember '(:host "wedd") '(4 5 6))
717 ;;; (auth-source-remembered-p '(:host "wedd"))
718 ;;; (auth-source-remember '(:host "xedd") '(1 2 3))
719 ;;; (auth-source-remembered-p '(:host "xedd"))
720 ;;; (auth-source-remembered-p '(:host "zedd"))
721 ;;; (auth-source-recall '(:host "xedd"))
722 ;;; (auth-source-recall '(:host t))
723 ;;; (auth-source-forget+ :host t)
725 (defun* auth-source-forget+ (&rest spec &allow-other-keys)
726 "Forget any cached data matching SPEC. Returns forgotten count.
728 This is not a full `auth-source-search' spec but works similarly.
729 For instance, \(:host \"myhost\" \"yourhost\") would find all the
730 cached data that was found with a search for those two hosts,
731 while \(:host t) would find all host entries."
734 (loop for sym being the symbols of password-data
735 ;; when the symbol name matches with auth-source-magic
736 when (and (setq sname (symbol-name sym))
737 (string-match (concat "^" auth-source-magic "\\(.+\\)")
739 ;; and the spec matches what was stored in the cache
740 (auth-source-specmatchp spec (read (match-string 1 sname))))
743 (password-cache-remove sname)
747 (defun auth-source-specmatchp (spec stored)
748 (let ((keys (loop for i below (length spec) by 2
749 collect (nth i spec))))
752 (unless (auth-source-search-collection (plist-get stored key)
753 (plist-get spec key))
757 ;;; (auth-source-pick-first-password :host "z.lifelogs.com")
758 ;;; (auth-source-pick-first-password :port "imap")
759 (defun auth-source-pick-first-password (&rest spec)
760 "Pick the first secret found from applying SPEC to `auth-source-search'."
761 (let* ((result (nth 0 (apply 'auth-source-search (plist-put spec :max 1))))
762 (secret (plist-get result :secret)))
764 (if (functionp secret)
768 ;; (auth-source-format-prompt "test %u %h %p" '((?u "user") (?h "host")))
769 (defun auth-source-format-prompt (prompt alist)
770 "Format PROMPT using %x (for any character x) specifiers in ALIST."
772 (let ((c (nth 0 cell))
775 (setq prompt (replace-regexp-in-string (format "%%%c" c)
780 (defun auth-source-ensure-strings (values)
781 (unless (listp values)
782 (setq values (list values)))
783 (mapcar (lambda (value)
789 ;;; Backend specific parsing: netrc/authinfo backend
791 (defvar auth-source-netrc-cache nil)
793 ;;; (auth-source-netrc-parse "~/.authinfo.gpg")
794 (defun* auth-source-netrc-parse (&rest
796 &key file max host user port delete require
798 "Parse FILE and return a list of all entries in the file.
799 Note that the MAX parameter is used so we can exit the parse early."
801 ;; We got already parsed contents; just return it.
803 (when (file-exists-p file)
804 (setq port (auth-source-ensure-strings port))
806 (let* ((tokens '("machine" "host" "default" "login" "user"
807 "password" "account" "macdef" "force"
809 (max (or max 5000)) ; sanity check: default to stop at 5K
811 (cached (cdr-safe (assoc file auth-source-netrc-cache)))
812 (cached-mtime (plist-get cached :mtime))
813 (cached-secrets (plist-get cached :secret))
814 alist elem result pair)
816 (if (and (functionp cached-secrets)
818 (nth 5 (file-attributes file))))
820 (auth-source-do-trivia
821 "auth-source-netrc-parse: using CACHED file data for %s"
823 (insert (funcall cached-secrets)))
824 (insert-file-contents file)
825 ;; cache all netrc files (used to be just .gpg files)
826 ;; Store the contents of the file heavily encrypted in memory.
827 ;; (note for the irony-impaired: they are just obfuscated)
828 (aput 'auth-source-netrc-cache file
829 (list :mtime (nth 5 (file-attributes file))
830 :secret (lexical-let ((v (rot13-string
831 (base64-encode-string
833 (lambda () (base64-decode-string
834 (rot13-string v)))))))
835 (goto-char (point-min))
836 ;; Go through the file, line by line.
837 (while (and (not (eobp))
840 (narrow-to-region (point) (point-at-eol))
841 ;; For each line, get the tokens and values.
843 (skip-chars-forward "\t ")
844 ;; Skip lines that begin with a "#".
845 (if (eq (char-after) ?#)
846 (goto-char (point-max))
849 (if (= (following-char) ?\")
850 (read (current-buffer))
852 (point) (progn (skip-chars-forward "^\t ")
855 ((equal elem "macdef")
856 ;; We skip past the macro definition.
858 (while (and (zerop (forward-line 1))
860 (narrow-to-region (point) (point)))
861 ((member elem tokens)
862 ;; Tokens that don't have a following value are ignored,
864 (when (and pair (or (cdr pair)
865 (equal (car pair) "default")))
867 (setq pair (list elem)))
869 ;; Values that haven't got a preceding token are ignored.
873 (setq pair nil)))))))
877 (auth-source-search-collection
880 (aget alist "machine")
883 (auth-source-search-collection
887 (aget alist "account")
890 (auth-source-search-collection
894 (aget alist "protocol")
897 ;; the required list of keys is nil, or
899 ;; every element of require is in the normalized list
900 (let ((normalized (nth 0 (auth-source-netrc-normalize
902 (loop for req in require
903 always (plist-get normalized req)))))
905 (push (nreverse alist) result)
906 ;; to delete a line, we just comment it out
908 (goto-char (point-min))
917 (when auth-source-gpg-encrypt-to
918 ;; (see bug#7487) making `epa-file-encrypt-to' local to
919 ;; this buffer lets epa-file skip the key selection query
920 ;; (see the `local-variable-p' check in
921 ;; `epa-file-write-region').
922 (unless (local-variable-p 'epa-file-encrypt-to (current-buffer))
923 (make-local-variable 'epa-file-encrypt-to))
924 (if (listp auth-source-gpg-encrypt-to)
925 (setq epa-file-encrypt-to auth-source-gpg-encrypt-to)))
927 ;; ask AFTER we've successfully opened the file
928 (when (y-or-n-p (format "Save file %s? (%d deletions)"
930 (write-region (point-min) (point-max) file nil 'silent)
931 (auth-source-do-debug
932 "auth-source-netrc-parse: modified %d lines in %s"
935 (nreverse result))))))
937 (defun auth-source-netrc-normalize (alist)
938 (mapcar (lambda (entry)
940 (while (setq item (pop entry))
945 (setq k (cond ((member k '("machine")) "host")
946 ((member k '("login" "account")) "user")
947 ((member k '("protocol")) "port")
948 ((member k '("password")) "secret")
951 ;; send back the secret in a function (lexical binding)
952 (when (equal k "secret")
953 (setq v (lexical-let ((v v))
956 (setq ret (plist-put ret
957 (intern (concat ":" k))
963 ;;; (setq secret (plist-get (nth 0 (auth-source-search :host t :type 'netrc :K 1 :max 1)) :secret))
966 (defun* auth-source-netrc-search (&rest
968 &key backend require create delete
969 type max host user port
971 "Given a property list SPEC, return search matches from the :backend.
972 See `auth-source-search' for details on SPEC."
973 ;; just in case, check that the type is correct (null or same as the backend)
974 (assert (or (null type) (eq type (oref backend type)))
975 t "Invalid netrc search: %s %s")
977 (let ((results (auth-source-netrc-normalize
978 (auth-source-netrc-parse
982 :file (oref backend source)
985 :port (or port t)))))
987 ;; if we need to create an entry AND none were found to match
991 ;; create based on the spec and record the value
993 ;; if the user did not want to create the entry
994 ;; in the file, it will be returned
995 (apply (slot-value backend 'create-function) spec)
996 ;; if not, we do the search again without :create
997 ;; to get the updated data.
999 ;; the result will be returned, even if the search fails
1000 (apply 'auth-source-netrc-search
1001 (plist-put spec :create nil)))))
1004 (defun auth-source-netrc-element-or-first (v)
1009 ;;; (auth-source-search :host "nonesuch" :type 'netrc :max 1 :create t)
1010 ;;; (auth-source-search :host "nonesuch" :type 'netrc :max 1 :create t :create-extra-keys '((A "default A") (B)))
1012 (defun* auth-source-netrc-create (&rest spec
1014 secret host user port create
1016 (let* ((base-required '(host user port secret))
1017 ;; we know (because of an assertion in auth-source-search) that the
1018 ;; :create parameter is either t or a list (which includes nil)
1019 (create-extra (if (eq t create) nil create))
1020 (required (append base-required create-extra))
1021 (file (oref backend source))
1023 ;; `valist' is an alist
1025 ;; `artificial' will be returned if no creation is needed
1028 ;; only for base required elements (defined as function parameters):
1029 ;; fill in the valist with whatever data we may have from the search
1030 ;; we complete the first value if it's a list and use the value otherwise
1031 (dolist (br base-required)
1032 (when (symbol-value br)
1033 (let ((br-choice (cond
1034 ;; all-accepting choice (predicate is t)
1035 ((eq t (symbol-value br)) nil)
1036 ;; just the value otherwise
1037 (t (symbol-value br)))))
1039 (aput 'valist br br-choice)))))
1041 ;; for extra required elements, see if the spec includes a value for them
1042 (dolist (er create-extra)
1043 (let ((name (concat ":" (symbol-name er)))
1044 (keys (loop for i below (length spec) by 2
1045 collect (nth i spec))))
1047 (when (equal (symbol-name k) name)
1048 (aput 'valist er (plist-get spec k))))))
1050 ;; for each required element
1051 (dolist (r required)
1052 (let* ((data (aget valist r))
1053 ;; take the first element if the data is a list
1054 (data (auth-source-netrc-element-or-first data))
1055 ;; this is the default to be offered
1056 (given-default (aget auth-source-creation-defaults r))
1057 ;; the default supplementals are simple:
1058 ;; for the user, try `given-default' and then (user-login-name);
1059 ;; otherwise take `given-default'
1061 ((and (not given-default) (eq r 'user))
1064 (printable-defaults (list
1067 (auth-source-netrc-element-or-first
1068 (aget valist 'user))
1069 (plist-get artificial :user)
1073 (auth-source-netrc-element-or-first
1074 (aget valist 'host))
1075 (plist-get artificial :host)
1079 (auth-source-netrc-element-or-first
1080 (aget valist 'port))
1081 (plist-get artificial :port)
1083 (prompt (or (aget auth-source-creation-prompts r)
1085 (secret "%p password for %u@%h: ")
1086 (user "%p user name for %h: ")
1087 (host "%p host name for user %u: ")
1088 (port "%p port for %u@%h: "))
1089 (format "Enter %s (%%u@%%h:%%p): " r)))
1090 (prompt (auth-source-format-prompt
1092 `((?u ,(aget printable-defaults 'user))
1093 (?h ,(aget printable-defaults 'host))
1094 (?p ,(aget printable-defaults 'port))))))
1096 ;; Store the data, prompting for the password if needed.
1099 ((and (null data) (eq r 'secret))
1100 ;; Special case prompt for passwords.
1101 (read-passwd prompt))
1105 (if (string-match ": *\\'" prompt)
1106 (concat (substring prompt 0 (match-beginning 0))
1107 " (default " default "): ")
1108 (concat prompt "(default " default ") "))))
1109 (read-string prompt nil nil default))
1110 (t (or data default))))
1113 (setq artificial (plist-put artificial
1114 (intern (concat ":" (symbol-name r)))
1116 (lexical-let ((data data))
1120 ;; When r is not an empty string...
1121 (when (and (stringp data)
1122 (< 0 (length data)))
1123 ;; this function is not strictly necessary but I think it
1124 ;; makes the code clearer -tzz
1125 (let ((printer (lambda ()
1126 ;; append the key (the symbol name of r)
1127 ;; and the value in r
1130 (if (zerop (length add)) "" " ")
1131 ;; remap auth-source tokens to netrc
1136 (port "port") ; redundant but clearer
1137 (t (symbol-name r)))
1138 ;; the value will be printed in %S format
1140 (setq add (concat add (funcall printer)))))))
1145 (lexical-let ((file file)
1147 (lambda () (auth-source-netrc-saver file add))))
1151 ;;(funcall (plist-get (nth 0 (auth-source-search :host '("nonesuch2") :user "tzz" :port "imap" :create t :max 1)) :save-function))
1152 (defun auth-source-netrc-saver (file add)
1153 "Save a line ADD in FILE, prompting along the way.
1154 Respects `auth-source-save-behavior'. Uses
1155 `auth-source-netrc-cache' to avoid prompting more than once."
1156 (let* ((key (format "%s %s" file (rfc2104-hash 'md5 64 16 file add)))
1157 (cached (assoc key auth-source-netrc-cache)))
1160 (auth-source-do-trivia
1161 "auth-source-netrc-saver: found previous run for key %s, returning"
1164 (when (file-exists-p file)
1165 (insert-file-contents file))
1166 (when auth-source-gpg-encrypt-to
1167 ;; (see bug#7487) making `epa-file-encrypt-to' local to
1168 ;; this buffer lets epa-file skip the key selection query
1169 ;; (see the `local-variable-p' check in
1170 ;; `epa-file-write-region').
1171 (unless (local-variable-p 'epa-file-encrypt-to (current-buffer))
1172 (make-local-variable 'epa-file-encrypt-to))
1173 (if (listp auth-source-gpg-encrypt-to)
1174 (setq epa-file-encrypt-to auth-source-gpg-encrypt-to)))
1175 ;; we want the new data to be found first, so insert at beginning
1176 (goto-char (point-min))
1178 ;; Ask AFTER we've successfully opened the file.
1179 (let ((prompt (format "Save auth info to file %s? " file))
1180 (done (not (eq auth-source-save-behavior 'ask)))
1181 (bufname "*auth-source Help*")
1184 (setq k (auth-source-read-char-choice prompt '(?y ?n ?N ?e ??)))
1188 (with-output-to-temp-buffer bufname
1190 (concat "(y)es, save\n"
1191 "(n)o but use the info\n"
1192 "(N)o and don't ask to save again\n"
1194 "(?) for help as you can see.\n"))
1195 ;; Why? Doesn't with-output-to-temp-buffer already do
1196 ;; the exact same thing anyway? --Stef
1197 (set-buffer standard-output)
1203 auth-source-save-behavior nil))
1204 (?e (setq add (read-string "Line to add: " add)))
1207 (when (get-buffer-window bufname)
1208 (delete-window (get-buffer-window bufname)))
1210 ;; Make sure the info is not saved.
1211 (when (null auth-source-save-behavior)
1214 (when (< 0 (length add))
1219 (write-region (point-min) (point-max) file nil 'silent)
1220 (auth-source-do-debug
1221 "auth-source-netrc-create: wrote 1 new line to %s"
1223 (message "Saved new authentication information to %s" file)
1225 (aput 'auth-source-netrc-cache key "ran"))))
1227 ;;; Backend specific parsing: Secrets API backend
1229 ;;; (let ((auth-sources '(default))) (auth-source-search :max 1 :create t))
1230 ;;; (let ((auth-sources '(default))) (auth-source-search :max 1 :delete t))
1231 ;;; (let ((auth-sources '(default))) (auth-source-search :max 1))
1232 ;;; (let ((auth-sources '(default))) (auth-source-search))
1233 ;;; (let ((auth-sources '("secrets:Login"))) (auth-source-search :max 1))
1234 ;;; (let ((auth-sources '("secrets:Login"))) (auth-source-search :max 1 :signon_realm "https://git.gnus.org/Git"))
1236 (defun* auth-source-secrets-search (&rest
1238 &key backend create delete label
1239 type max host user port
1241 "Search the Secrets API; spec is like `auth-source'.
1243 The :label key specifies the item's label. It is the only key
1244 that can specify a substring. Any :label value besides a string
1245 will allow any label.
1247 All other search keys must match exactly. If you need substring
1248 matching, do a wider search and narrow it down yourself.
1250 You'll get back all the properties of the token as a plist.
1252 Here's an example that looks for the first item in the 'Login'
1255 \(let ((auth-sources '(\"secrets:Login\")))
1256 (auth-source-search :max 1)
1258 Here's another that looks for the first item in the 'Login'
1259 Secrets collection whose label contains 'gnus':
1261 \(let ((auth-sources '(\"secrets:Login\")))
1262 (auth-source-search :max 1 :label \"gnus\")
1264 And this one looks for the first item in the 'Login' Secrets
1265 collection that's a Google Chrome entry for the git.gnus.org site
1266 authentication tokens:
1268 \(let ((auth-sources '(\"secrets:Login\")))
1269 (auth-source-search :max 1 :signon_realm \"https://git.gnus.org/Git\"))
1273 (assert (not create) nil
1274 "The Secrets API auth-source backend doesn't support creation yet")
1276 ;; (secrets-delete-item coll elt)
1277 (assert (not delete) nil
1278 "The Secrets API auth-source backend doesn't support deletion yet")
1280 (let* ((coll (oref backend source))
1281 (max (or max 5000)) ; sanity check: default to stop at 5K
1282 (ignored-keys '(:create :delete :max :backend :label))
1283 (search-keys (loop for i below (length spec) by 2
1284 unless (memq (nth i spec) ignored-keys)
1285 collect (nth i spec)))
1286 ;; build a search spec without the ignored keys
1287 ;; if a search key is nil or t (match anything), we skip it
1288 (search-spec (apply 'append (mapcar
1290 (if (or (null (plist-get spec k))
1291 (eq t (plist-get spec k)))
1293 (list k (plist-get spec k))))
1295 ;; needed keys (always including host, login, port, and secret)
1296 (returned-keys (mm-delete-duplicates (append
1297 '(:host :login :port :secret)
1299 (items (loop for item in (apply 'secrets-search-items coll search-spec)
1300 unless (and (stringp label)
1301 (not (string-match label item)))
1303 ;; TODO: respect max in `secrets-search-items', not after the fact
1304 (items (butlast items (- (length items) max)))
1305 ;; convert the item name to a full plist
1306 (items (mapcar (lambda (item)
1308 ;; make an entry for the secret (password) element
1311 (lexical-let ((v (secrets-get-secret coll item)))
1313 ;; rewrite the entry from ((k1 v1) (k2 v2)) to plist
1315 (mapcar (lambda (entry)
1316 (list (car entry) (cdr entry)))
1317 (secrets-get-attributes coll item)))))
1319 ;; ensure each item has each key in `returned-keys'
1320 (items (mapcar (lambda (plist)
1323 (mapcar (lambda (req)
1324 (if (plist-get plist req)
1332 (defun* auth-source-secrets-create (&rest
1334 &key backend type max host user port
1337 ;; (apply 'secrets-create-item (auth-get-source entry) name passwd spec)
1342 ;;; (auth-source-user-or-password '("login" "password") "imap.myhost.com" t "tzz")
1344 ;; deprecate the old interface
1345 (make-obsolete 'auth-source-user-or-password
1346 'auth-source-search "Emacs 24.1")
1347 (make-obsolete 'auth-source-forget-user-or-password
1348 'auth-source-forget "Emacs 24.1")
1350 (defun auth-source-user-or-password
1351 (mode host port &optional username create-missing delete-existing)
1352 "Find MODE (string or list of strings) matching HOST and PORT.
1354 DEPRECATED in favor of `auth-source-search'!
1356 USERNAME is optional and will be used as \"login\" in a search
1357 across the Secret Service API (see secrets.el) if the resulting
1358 items don't have a username. This means that if you search for
1359 username \"joe\" and it matches an item but the item doesn't have
1360 a :user attribute, the username \"joe\" will be returned.
1362 A non nil DELETE-EXISTING means deleting any matching password
1363 entry in the respective sources. This is useful only when
1364 CREATE-MISSING is non nil as well; the intended use case is to
1365 remove wrong password entries.
1367 If no matching entry is found, and CREATE-MISSING is non nil,
1368 the password will be retrieved interactively, and it will be
1369 stored in the password database which matches best (see
1372 MODE can be \"login\" or \"password\"."
1373 (auth-source-do-debug
1374 "auth-source-user-or-password: DEPRECATED get %s for %s (%s) + user=%s"
1375 mode host port username)
1377 (let* ((listy (listp mode))
1378 (mode (if listy mode (list mode)))
1380 (format "%s %s:%s %s" mode host port username)
1381 (format "%s %s:%s" mode host port)))
1382 (search (list :host host :port port))
1383 (search (if username (append search (list :user username)) search))
1384 (search (if create-missing
1385 (append search (list :create t))
1387 (search (if delete-existing
1388 (append search (list :delete t))
1390 ;; (found (if (not delete-existing)
1391 ;; (gethash cname auth-source-cache)
1392 ;; (remhash cname auth-source-cache)
1397 (auth-source-do-debug
1398 "auth-source-user-or-password: DEPRECATED cached %s=%s for %s (%s) + %s"
1400 ;; don't show the password
1401 (if (and (member "password" mode) t)
1405 found) ; return the found data
1406 ;; else, if not found, search with a max of 1
1407 (let ((choice (nth 0 (apply 'auth-source-search
1408 (append '(:max 1) search)))))
1412 ((equal "password" m)
1413 (push (if (plist-get choice :secret)
1414 (funcall (plist-get choice :secret))
1417 (push (plist-get choice :user) found)))))
1418 (setq found (nreverse found))
1419 (setq found (if listy found (car-safe found)))))
1423 (provide 'auth-source)
1425 ;;; auth-source.el ends here