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))
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 (defvar secrets-enabled)
69 (defgroup auth-source nil
70 "Authentication sources."
71 :version "23.1" ;; No Gnus
75 (defcustom auth-source-cache-expiry 7200
76 "How many seconds passwords are cached, or nil to disable
77 expiring. Overrides `password-cache-expiry' through a
80 :type '(choice (const :tag "Never" nil)
81 (const :tag "All Day" 86400)
82 (const :tag "2 Hours" 7200)
83 (const :tag "30 Minutes" 1800)
84 (integer :tag "Seconds")))
86 (defclass auth-source-backend ()
91 :documentation "The backend type.")
92 (source :initarg :source
95 :documentation "The backend source.")
100 :documentation "The backend host.")
105 :documentation "The backend user.")
110 :documentation "The backend protocol.")
111 (create-function :initarg :create-function
115 :documentation "The create function.")
116 (search-function :initarg :search-function
120 :documentation "The search function.")))
122 (defcustom auth-source-protocols '((imap "imap" "imaps" "143" "993")
123 (pop3 "pop3" "pop" "pop3s" "110" "995")
127 "List of authentication protocols and their names"
130 :version "23.2" ;; No Gnus
131 :type '(repeat :tag "Authentication Protocols"
132 (cons :tag "Protocol Entry"
133 (symbol :tag "Protocol")
135 (string :tag "Name")))))
137 ;;; generate all the protocols in a format Customize can use
138 ;;; TODO: generate on the fly from auth-source-protocols
139 (defconst auth-source-protocols-customize
141 (let ((p (car-safe a)))
143 :tag (upcase (symbol-name p))
145 auth-source-protocols))
147 (defvar auth-source-creation-defaults nil
148 "Defaults for creating token values. Usually let-bound.")
150 (defvar auth-source-creation-prompts nil
151 "Default prompts for token values. Usually let-bound.")
153 (make-obsolete 'auth-source-hide-passwords nil "Emacs 24.1")
155 (defcustom auth-source-save-behavior 'ask
156 "If set, auth-source will respect it for save behavior."
158 :version "23.2" ;; No Gnus
160 :tag "auth-source new token save behavior"
161 (const :tag "Always save" t)
162 (const :tag "Never save" nil)
163 (const :tag "Ask" ask)))
165 (defvar auth-source-magic "auth-source-magic ")
167 (defcustom auth-source-do-cache t
168 "Whether auth-source should cache information with `password-cache'."
170 :version "23.2" ;; No Gnus
173 (defcustom auth-source-debug nil
174 "Whether auth-source should log debug messages.
176 If the value is nil, debug messages are not logged.
178 If the value is t, debug messages are logged with `message'. In
179 that case, your authentication data will be in the clear (except
182 If the value is a function, debug messages are logged by calling
183 that function using the same arguments as `message'."
185 :version "23.2" ;; No Gnus
187 :tag "auth-source debugging mode"
188 (const :tag "Log using `message' to the *Messages* buffer" t)
189 (const :tag "Log all trivia with `message' to the *Messages* buffer"
191 (function :tag "Function that takes arguments like `message'")
192 (const :tag "Don't log anything" nil)))
194 (defcustom auth-sources '("~/.authinfo.gpg" "~/.authinfo" "~/.netrc")
195 "List of authentication sources.
197 The default will get login and password information from
198 \"~/.authinfo.gpg\", which you should set up with the EPA/EPG
199 packages to be encrypted. If that file doesn't exist, it will
200 try the unencrypted version \"~/.authinfo\" and the famous
203 See the auth.info manual for details.
205 Each entry is the authentication type with optional properties.
207 It's best to customize this with `M-x customize-variable' because the choices
208 can get pretty complex."
210 :version "24.1" ;; No Gnus
211 :type `(repeat :tag "Authentication Sources"
213 (string :tag "Just a file")
214 (const :tag "Default Secrets API Collection" 'default)
215 (const :tag "Login Secrets API Collection" "secrets:Login")
216 (const :tag "Temp Secrets API Collection" "secrets:session")
217 (list :tag "Source definition"
218 (const :format "" :value :source)
219 (choice :tag "Authentication backend choice"
220 (string :tag "Authentication Source (file)")
222 :tag "Secret Service API/KWallet/GNOME Keyring"
223 (const :format "" :value :secrets)
224 (choice :tag "Collection to use"
225 (string :tag "Collection name")
226 (const :tag "Default" 'default)
227 (const :tag "Login" "Login")
229 :tag "Temporary" "session"))))
230 (repeat :tag "Extra Parameters" :inline t
231 (choice :tag "Extra parameter"
234 (const :format "" :value :host)
235 (choice :tag "Host (machine) choice"
238 :tag "Regular expression")))
241 (const :format "" :value :port)
245 ,@auth-source-protocols-customize))
246 (list :tag "User" :inline t
247 (const :format "" :value :user)
248 (choice :tag "Personality/Username"
250 (string :tag "Name")))))))))
252 (defcustom auth-source-gpg-encrypt-to t
253 "List of recipient keys that `authinfo.gpg' encrypted to.
254 If the value is not a list, symmetric encryption will be used."
256 :version "24.1" ;; No Gnus
257 :type '(choice (const :tag "Symmetric encryption" t)
258 (repeat :tag "Recipient public keys"
259 (string :tag "Recipient public key"))))
261 ;; temp for debugging
262 ;; (unintern 'auth-source-protocols)
263 ;; (unintern 'auth-sources)
264 ;; (customize-variable 'auth-sources)
265 ;; (setq auth-sources nil)
266 ;; (format "%S" auth-sources)
267 ;; (customize-variable 'auth-source-protocols)
268 ;; (setq auth-source-protocols nil)
269 ;; (format "%S" auth-source-protocols)
270 ;; (auth-source-pick nil :host "a" :port 'imap)
271 ;; (auth-source-user-or-password "login" "imap.myhost.com" 'imap)
272 ;; (auth-source-user-or-password "password" "imap.myhost.com" 'imap)
273 ;; (auth-source-user-or-password-imap "login" "imap.myhost.com")
274 ;; (auth-source-user-or-password-imap "password" "imap.myhost.com")
275 ;; (auth-source-protocol-defaults 'imap)
277 ;; (let ((auth-source-debug 'debug)) (auth-source-do-debug "hello"))
278 ;; (let ((auth-source-debug t)) (auth-source-do-debug "hello"))
279 ;; (let ((auth-source-debug nil)) (auth-source-do-debug "hello"))
280 (defun auth-source-do-debug (&rest msg)
281 (when auth-source-debug
282 (apply 'auth-source-do-warn msg)))
284 (defun auth-source-do-trivia (&rest msg)
285 (when (or (eq auth-source-debug 'trivia)
286 (functionp auth-source-debug))
287 (apply 'auth-source-do-warn msg)))
289 (defun auth-source-do-warn (&rest msg)
291 ;; set logger to either the function in auth-source-debug or 'message
292 ;; note that it will be 'message if auth-source-debug is nil
293 (if (functionp auth-source-debug)
299 ;;; (auth-source-read-char-choice "enter choice? " '(?a ?b ?q))
300 (defun auth-source-read-char-choice (prompt choices)
301 "Read one of CHOICES by `read-char-choice', or `read-char'.
302 `dropdown-list' support is disabled because it doesn't work reliably.
303 Only one of CHOICES will be returned. The PROMPT is augmented
304 with \"[a/b/c] \" if CHOICES is '\(?a ?b ?c\)."
306 (let* ((prompt-choices
307 (apply 'concat (loop for c in choices
308 collect (format "%c/" c))))
309 (prompt-choices (concat "[" (substring prompt-choices 0 -1) "] "))
310 (full-prompt (concat prompt prompt-choices))
313 (while (not (memq k choices))
315 ((fboundp 'read-char-choice)
316 (read-char-choice full-prompt choices))
317 (t (message "%s" full-prompt)
318 (setq k (read-char))))))
321 ;; (auth-source-pick nil :host "any" :port 'imap :user "joe")
322 ;; (auth-source-pick t :host "any" :port 'imap :user "joe")
323 ;; (setq auth-sources '((:source (:secrets default) :host t :port t :user "joe")
324 ;; (:source (:secrets "session") :host t :port t :user "joe")
325 ;; (:source (:secrets "Login") :host t :port t)
326 ;; (:source "~/.authinfo.gpg" :host t :port t)))
328 ;; (setq auth-sources '((:source (:secrets default) :host t :port t :user "joe")
329 ;; (:source (:secrets "session") :host t :port t :user "joe")
330 ;; (:source (:secrets "Login") :host t :port t)
333 ;; (setq auth-sources '((:source "~/.authinfo.gpg" :host t :port t)))
335 ;; (auth-source-backend-parse "myfile.gpg")
336 ;; (auth-source-backend-parse 'default)
337 ;; (auth-source-backend-parse "secrets:Login")
339 (defun auth-source-backend-parse (entry)
340 "Creates an auth-source-backend from an ENTRY in `auth-sources'."
341 (auth-source-backend-parse-parameters
344 ;; take 'default and recurse to get it as a Secrets API default collection
345 ;; matching any user, host, and protocol
347 (auth-source-backend-parse '(:source (:secrets default))))
348 ;; take secrets:XYZ and recurse to get it as Secrets API collection "XYZ"
349 ;; matching any user, host, and protocol
350 ((and (stringp entry) (string-match "^secrets:\\(.+\\)" entry))
351 (auth-source-backend-parse `(:source (:secrets ,(match-string 1 entry)))))
352 ;; take just a file name and recurse to get it as a netrc file
353 ;; matching any user, host, and protocol
355 (auth-source-backend-parse `(:source ,entry)))
357 ;; a file name with parameters
358 ((stringp (plist-get entry :source))
360 (plist-get entry :source)
361 :source (plist-get entry :source)
363 :search-function 'auth-source-netrc-search
364 :create-function 'auth-source-netrc-create))
366 ;; the Secrets API. We require the package, in order to have a
367 ;; defined value for `secrets-enabled'.
369 (not (null (plist-get entry :source))) ; the source must not be nil
370 (listp (plist-get entry :source)) ; and it must be a list
371 (require 'secrets nil t) ; and we must load the Secrets API
372 secrets-enabled) ; and that API must be enabled
374 ;; the source is either the :secrets key in ENTRY or
375 ;; if that's missing or nil, it's "session"
376 (let ((source (or (plist-get (plist-get entry :source) :secrets)
379 ;; if the source is a symbol, we look for the alias named so,
380 ;; and if that alias is missing, we use "Login"
381 (when (symbolp source)
382 (setq source (or (secrets-get-alias (symbol-name source))
385 (if (featurep 'secrets)
387 (format "Secrets API (%s)" source)
390 :search-function 'auth-source-secrets-search
391 :create-function 'auth-source-secrets-create)
393 "auth-source-backend-parse: no Secrets API, ignoring spec: %S" entry)
395 (format "Ignored Secrets API (%s)" source)
402 "auth-source-backend-parse: invalid backend spec: %S" entry)
408 (defun auth-source-backend-parse-parameters (entry backend)
409 "Fills in the extra auth-source-backend parameters of ENTRY.
410 Using the plist ENTRY, get the :host, :port, and :user search
412 (let ((entry (if (stringp entry)
416 (when (setq val (plist-get entry :host))
417 (oset backend host val))
418 (when (setq val (plist-get entry :user))
419 (oset backend user val))
420 (when (setq val (plist-get entry :port))
421 (oset backend port val)))
424 ;; (mapcar 'auth-source-backend-parse auth-sources)
426 (defun* auth-source-search (&rest spec
427 &key type max host user port secret
428 require create delete
430 "Search or modify authentication backends according to SPEC.
432 This function parses `auth-sources' for matches of the SPEC
433 plist. It can optionally create or update an authentication
434 token if requested. A token is just a standard Emacs property
435 list with a :secret property that can be a function; all the
436 other properties will always hold scalar values.
438 Typically the :secret property, if present, contains a password.
440 Common search keys are :max, :host, :port, and :user. In
441 addition, :create specifies how tokens will be or created.
442 Finally, :type can specify which backend types you want to check.
444 A string value is always matched literally. A symbol is matched
445 as its string value, literally. All the SPEC values can be
446 single values (symbol or string) or lists thereof (in which case
447 any of the search terms matches).
449 :create t means to create a token if possible.
451 A new token will be created if no matching tokens were found.
452 The new token will have only the keys the backend requires. For
453 the netrc backend, for instance, that's the user, host, and
458 \(let ((auth-source-creation-defaults '((user . \"defaultUser\")
459 (A . \"default A\"))))
460 (auth-source-search :host \"mine\" :type 'netrc :max 1
461 :P \"pppp\" :Q \"qqqq\"
466 \"Search for any entry matching host 'mine' in backends of type
467 'netrc', maximum one result.
469 Create a new entry if you found none. The netrc backend will
470 automatically require host, user, and port. The host will be
471 'mine'. We prompt for the user with default 'defaultUser' and
472 for the port without a default. We will not prompt for A, Q,
473 or P. The resulting token will only have keys user, host, and
476 :create '(A B C) also means to create a token if possible.
478 The behavior is like :create t but if the list contains any
479 parameter, that parameter will be required in the resulting
480 token. The value for that parameter will be obtained from the
481 search parameters or from user input. If any queries are needed,
482 the alist `auth-source-creation-defaults' will be checked for the
483 default value. If the user, host, or port are missing, the alist
484 `auth-source-creation-prompts' will be used to look up the
485 prompts IN THAT ORDER (so the 'user prompt will be queried first,
486 then 'host, then 'port, and finally 'secret). Each prompt string
487 can use %u, %h, and %p to show the user, host, and port.
491 \(let ((auth-source-creation-defaults '((user . \"defaultUser\")
492 (A . \"default A\")))
493 (auth-source-creation-prompts
494 '((password . \"Enter IMAP password for %h:%p: \"))))
495 (auth-source-search :host '(\"nonesuch\" \"twosuch\") :type 'netrc :max 1
496 :P \"pppp\" :Q \"qqqq\"
501 \"Search for any entry matching host 'nonesuch'
502 or 'twosuch' in backends of type 'netrc', maximum one result.
504 Create a new entry if you found none. The netrc backend will
505 automatically require host, user, and port. The host will be
506 'nonesuch' and Q will be 'qqqq'. We prompt for the password
507 with the shown prompt. We will not prompt for Q. The resulting
508 token will have keys user, host, port, A, B, and Q. It will not
509 have P with any value, even though P is used in the search to
510 find only entries that have P set to 'pppp'.\"
512 When multiple values are specified in the search parameter, the
513 user is prompted for which one. So :host (X Y Z) would ask the
514 user to choose between X, Y, and Z.
516 This creation can fail if the search was not specific enough to
517 create a new token (it's up to the backend to decide that). You
518 should `catch' the backend-specific error as usual. Some
519 backends (netrc, at least) will prompt the user rather than throw
522 :require (A B C) means that only results that contain those
523 tokens will be returned. Thus for instance requiring :secret
524 will ensure that any results will actually have a :secret
527 :delete t means to delete any found entries. nil by default.
528 Use `auth-source-delete' in ELisp code instead of calling
529 `auth-source-search' directly with this parameter.
531 :type (X Y Z) will check only those backend types. 'netrc and
532 'secrets are the only ones supported right now.
534 :max N means to try to return at most N items (defaults to 1).
535 When 0 the function will return just t or nil to indicate if any
536 matches were found. More than N items may be returned, depending
537 on the search and the backend.
539 :host (X Y Z) means to match only hosts X, Y, or Z according to
540 the match rules above. Defaults to t.
542 :user (X Y Z) means to match only users X, Y, or Z according to
543 the match rules above. Defaults to t.
545 :port (P Q R) means to match only protocols P, Q, or R.
548 :K (V1 V2 V3) for any other key K will match values V1, V2, or
549 V3 (note the match rules above).
551 The return value is a list with at most :max tokens. Each token
552 is a plist with keys :backend :host :port :user, plus any other
553 keys provided by the backend (notably :secret). But note the
554 exception for :max 0, which see above.
556 The token can hold a :save-function key. If you call that, the
557 user will be prompted to save the data to the backend. You can't
558 request that this should happen right after creation, because
559 `auth-source-search' has no way of knowing if the token is
560 actually useful. So the caller must arrange to call this function.
562 The token's :secret key can hold a function. In that case you
563 must call it to obtain the actual value."
564 (let* ((backends (mapcar 'auth-source-backend-parse auth-sources))
566 (ignored-keys '(:require :create :delete :max))
567 (keys (loop for i below (length spec) by 2
568 unless (memq (nth i spec) ignored-keys)
569 collect (nth i spec)))
570 (cached (auth-source-remembered-p spec))
571 ;; note that we may have cached results but found is still nil
572 ;; (there were no results from the search)
573 (found (auth-source-recall spec))
574 filtered-backends accessor-key backend)
576 (if (and cached auth-source-do-cache)
577 (auth-source-do-debug
578 "auth-source-search: found %d CACHED results matching %S"
582 (or (eq t create) (listp create)) t
583 "Invalid auth-source :create parameter (must be t or a list): %s %s")
587 "Invalid auth-source :require parameter (must be a list): %s")
589 (setq filtered-backends (copy-sequence backends))
590 (dolist (backend backends)
592 ;; ignore invalid slots
593 (condition-case signal
594 (unless (eval `(auth-source-search-collection
596 (oref backend ,key)))
597 (setq filtered-backends (delq backend filtered-backends))
599 (invalid-slot-name))))
601 (auth-source-do-trivia
602 "auth-source-search: found %d backends matching %S"
603 (length filtered-backends) spec)
605 ;; (debug spec "filtered" filtered-backends)
606 ;; First go through all the backends without :create, so we can
608 (setq found (auth-source-search-backends filtered-backends
612 ;; create is always nil here
616 (auth-source-do-debug
617 "auth-source-search: found %d results (max %d) matching %S"
618 (length found) max spec)
620 ;; If we didn't find anything, then we allow the backend(s) to
621 ;; create the entries.
624 (setq found (auth-source-search-backends filtered-backends
630 (auth-source-do-debug
631 "auth-source-search: CREATED %d results (max %d) matching %S"
632 (length found) max spec))
634 ;; note we remember the lack of result too, if it's applicable
635 (when auth-source-do-cache
636 (auth-source-remember spec found)))
640 (defun auth-source-search-backends (backends spec max create delete require)
642 (dolist (backend backends)
643 (when (> max (length matches)) ; when we need more matches...
644 (let* ((bmatches (apply
645 (slot-value backend 'search-function)
647 ;; note we're overriding whatever the spec
648 ;; has for :require, :create, and :delete
654 (auth-source-do-trivia
655 "auth-source-search-backend: got %d (max %d) in %s:%s matching %S"
656 (length bmatches) max
657 (slot-value backend :type)
658 (slot-value backend :source)
660 (setq matches (append matches bmatches))))))
663 ;;; (auth-source-search :max 1)
664 ;;; (funcall (plist-get (nth 0 (auth-source-search :max 1)) :secret))
665 ;;; (auth-source-search :host "nonesuch" :type 'netrc :K 1)
666 ;;; (auth-source-search :host "nonesuch" :type 'secrets)
668 (defun* auth-source-delete (&rest spec
671 "Delete entries from the authentication backends according to SPEC.
672 Calls `auth-source-search' with the :delete property in SPEC set to t.
673 The backend may not actually delete the entries.
675 Returns the deleted entries."
676 (auth-source-search (plist-put spec :delete t)))
678 (defun auth-source-search-collection (collection value)
679 "Returns t is VALUE is t or COLLECTION is t or contains VALUE."
680 (when (and (atom collection) (not (eq t collection)))
681 (setq collection (list collection)))
683 ;; (debug :collection collection :value value)
684 (or (eq collection t)
686 (equal collection value)
687 (member value collection)))
689 (defun auth-source-forget-all-cached ()
690 "Forget all cached auth-source data."
692 (loop for sym being the symbols of password-data
693 ;; when the symbol name starts with auth-source-magic
694 when (string-match (concat "^" auth-source-magic)
697 do (password-cache-remove (symbol-name sym))))
699 (defun auth-source-remember (spec found)
700 "Remember FOUND search results for SPEC."
701 (let ((password-cache-expiry auth-source-cache-expiry))
703 (concat auth-source-magic (format "%S" spec)) found)))
705 (defun auth-source-recall (spec)
706 "Recall FOUND search results for SPEC."
707 (password-read-from-cache
708 (concat auth-source-magic (format "%S" spec))))
710 (defun auth-source-remembered-p (spec)
711 "Check if SPEC is remembered."
713 (concat auth-source-magic (format "%S" spec))))
715 (defun auth-source-forget (spec)
716 "Forget any cached data matching SPEC exactly.
718 This is the same SPEC you passed to `auth-source-search'.
719 Returns t or nil for forgotten or not found."
720 (password-cache-remove (concat auth-source-magic (format "%S" spec))))
722 ;;; (loop for sym being the symbols of password-data when (string-match (concat "^" auth-source-magic) (symbol-name sym)) collect (symbol-name sym))
724 ;;; (auth-source-remember '(:host "wedd") '(4 5 6))
725 ;;; (auth-source-remembered-p '(:host "wedd"))
726 ;;; (auth-source-remember '(:host "xedd") '(1 2 3))
727 ;;; (auth-source-remembered-p '(:host "xedd"))
728 ;;; (auth-source-remembered-p '(:host "zedd"))
729 ;;; (auth-source-recall '(:host "xedd"))
730 ;;; (auth-source-recall '(:host t))
731 ;;; (auth-source-forget+ :host t)
733 (defun* auth-source-forget+ (&rest spec &allow-other-keys)
734 "Forget any cached data matching SPEC. Returns forgotten count.
736 This is not a full `auth-source-search' spec but works similarly.
737 For instance, \(:host \"myhost\" \"yourhost\") would find all the
738 cached data that was found with a search for those two hosts,
739 while \(:host t) would find all host entries."
742 (loop for sym being the symbols of password-data
743 ;; when the symbol name matches with auth-source-magic
744 when (and (setq sname (symbol-name sym))
745 (string-match (concat "^" auth-source-magic "\\(.+\\)")
747 ;; and the spec matches what was stored in the cache
748 (auth-source-specmatchp spec (read (match-string 1 sname))))
751 (password-cache-remove sname)
755 (defun auth-source-specmatchp (spec stored)
756 (let ((keys (loop for i below (length spec) by 2
757 collect (nth i spec))))
760 (unless (auth-source-search-collection (plist-get stored key)
761 (plist-get spec key))
765 ;;; (auth-source-pick-first-password :host "z.lifelogs.com")
766 ;;; (auth-source-pick-first-password :port "imap")
767 (defun auth-source-pick-first-password (&rest spec)
768 "Pick the first secret found from applying SPEC to `auth-source-search'."
769 (let* ((result (nth 0 (apply 'auth-source-search (plist-put spec :max 1))))
770 (secret (plist-get result :secret)))
772 (if (functionp secret)
776 ;; (auth-source-format-prompt "test %u %h %p" '((?u "user") (?h "host")))
777 (defun auth-source-format-prompt (prompt alist)
778 "Format PROMPT using %x (for any character x) specifiers in ALIST."
780 (let ((c (nth 0 cell))
783 (setq prompt (replace-regexp-in-string (format "%%%c" c) v prompt)))))
786 (defun auth-source-ensure-strings (values)
787 (unless (listp values)
788 (setq values (list values)))
789 (mapcar (lambda (value)
795 ;;; Backend specific parsing: netrc/authinfo backend
797 (defvar auth-source-netrc-cache nil)
799 ;;; (auth-source-netrc-parse "~/.authinfo.gpg")
800 (defun* auth-source-netrc-parse (&rest
802 &key file max host user port delete require
804 "Parse FILE and return a list of all entries in the file.
805 Note that the MAX parameter is used so we can exit the parse early."
807 ;; We got already parsed contents; just return it.
809 (when (file-exists-p file)
810 (setq port (auth-source-ensure-strings port))
812 (let* ((tokens '("machine" "host" "default" "login" "user"
813 "password" "account" "macdef" "force"
815 (max (or max 5000)) ; sanity check: default to stop at 5K
817 (cached (cdr-safe (assoc file auth-source-netrc-cache)))
818 (cached-mtime (plist-get cached :mtime))
819 (cached-secrets (plist-get cached :secret))
820 alist elem result pair)
822 (if (and (functionp cached-secrets)
824 (nth 5 (file-attributes file))))
826 (auth-source-do-trivia
827 "auth-source-netrc-parse: using CACHED file data for %s"
829 (insert (funcall cached-secrets)))
830 (insert-file-contents file)
831 ;; cache all netrc files (used to be just .gpg files)
832 ;; Store the contents of the file heavily encrypted in memory.
833 ;; (note for the irony-impaired: they are just obfuscated)
834 (aput 'auth-source-netrc-cache file
835 (list :mtime (nth 5 (file-attributes file))
836 :secret (lexical-let ((v (rot13-string
837 (base64-encode-string
839 (lambda () (base64-decode-string
840 (rot13-string v)))))))
841 (goto-char (point-min))
842 ;; Go through the file, line by line.
843 (while (and (not (eobp))
846 (narrow-to-region (point) (point-at-eol))
847 ;; For each line, get the tokens and values.
849 (skip-chars-forward "\t ")
850 ;; Skip lines that begin with a "#".
851 (if (eq (char-after) ?#)
852 (goto-char (point-max))
855 (if (= (following-char) ?\")
856 (read (current-buffer))
858 (point) (progn (skip-chars-forward "^\t ")
861 ((equal elem "macdef")
862 ;; We skip past the macro definition.
864 (while (and (zerop (forward-line 1))
866 (narrow-to-region (point) (point)))
867 ((member elem tokens)
868 ;; Tokens that don't have a following value are ignored,
870 (when (and pair (or (cdr pair)
871 (equal (car pair) "default")))
873 (setq pair (list elem)))
875 ;; Values that haven't got a preceding token are ignored.
879 (setq pair nil)))))))
883 (auth-source-search-collection
886 (aget alist "machine")
889 (auth-source-search-collection
893 (aget alist "account")
896 (auth-source-search-collection
900 (aget alist "protocol")
903 ;; the required list of keys is nil, or
905 ;; every element of require is in the normalized list
906 (let ((normalized (nth 0 (auth-source-netrc-normalize
908 (loop for req in require
909 always (plist-get normalized req)))))
911 (push (nreverse alist) result)
912 ;; to delete a line, we just comment it out
914 (goto-char (point-min))
923 (when auth-source-gpg-encrypt-to
924 ;; (see bug#7487) making `epa-file-encrypt-to' local to
925 ;; this buffer lets epa-file skip the key selection query
926 ;; (see the `local-variable-p' check in
927 ;; `epa-file-write-region').
928 (unless (local-variable-p 'epa-file-encrypt-to (current-buffer))
929 (make-local-variable 'epa-file-encrypt-to))
930 (if (listp auth-source-gpg-encrypt-to)
931 (setq epa-file-encrypt-to auth-source-gpg-encrypt-to)))
933 ;; ask AFTER we've successfully opened the file
934 (when (y-or-n-p (format "Save file %s? (%d deletions)"
936 (write-region (point-min) (point-max) file nil 'silent)
937 (auth-source-do-debug
938 "auth-source-netrc-parse: modified %d lines in %s"
941 (nreverse result))))))
943 (defun auth-source-netrc-normalize (alist)
944 (mapcar (lambda (entry)
946 (while (setq item (pop entry))
951 (setq k (cond ((member k '("machine")) "host")
952 ((member k '("login" "account")) "user")
953 ((member k '("protocol")) "port")
954 ((member k '("password")) "secret")
957 ;; send back the secret in a function (lexical binding)
958 (when (equal k "secret")
959 (setq v (lexical-let ((v v))
962 (setq ret (plist-put ret
963 (intern (concat ":" k))
969 ;;; (setq secret (plist-get (nth 0 (auth-source-search :host t :type 'netrc :K 1 :max 1)) :secret))
972 (defun* auth-source-netrc-search (&rest
974 &key backend require create delete
975 type max host user port
977 "Given a property list SPEC, return search matches from the :backend.
978 See `auth-source-search' for details on SPEC."
979 ;; just in case, check that the type is correct (null or same as the backend)
980 (assert (or (null type) (eq type (oref backend type)))
981 t "Invalid netrc search: %s %s")
983 (let ((results (auth-source-netrc-normalize
984 (auth-source-netrc-parse
988 :file (oref backend source)
991 :port (or port t)))))
993 ;; if we need to create an entry AND none were found to match
997 ;; create based on the spec and record the value
999 ;; if the user did not want to create the entry
1000 ;; in the file, it will be returned
1001 (apply (slot-value backend 'create-function) spec)
1002 ;; if not, we do the search again without :create
1003 ;; to get the updated data.
1005 ;; the result will be returned, even if the search fails
1006 (apply 'auth-source-netrc-search
1007 (plist-put spec :create nil)))))
1010 (defun auth-source-netrc-element-or-first (v)
1015 ;;; (auth-source-search :host "nonesuch" :type 'netrc :max 1 :create t)
1016 ;;; (auth-source-search :host "nonesuch" :type 'netrc :max 1 :create t :create-extra-keys '((A "default A") (B)))
1018 (defun* auth-source-netrc-create (&rest spec
1020 secret host user port create
1022 (let* ((base-required '(host user port secret))
1023 ;; we know (because of an assertion in auth-source-search) that the
1024 ;; :create parameter is either t or a list (which includes nil)
1025 (create-extra (if (eq t create) nil create))
1026 (required (append base-required create-extra))
1027 (file (oref backend source))
1029 ;; `valist' is an alist
1031 ;; `artificial' will be returned if no creation is needed
1034 ;; only for base required elements (defined as function parameters):
1035 ;; fill in the valist with whatever data we may have from the search
1036 ;; we complete the first value if it's a list and use the value otherwise
1037 (dolist (br base-required)
1038 (when (symbol-value br)
1039 (let ((br-choice (cond
1040 ;; all-accepting choice (predicate is t)
1041 ((eq t (symbol-value br)) nil)
1042 ;; just the value otherwise
1043 (t (symbol-value br)))))
1045 (aput 'valist br br-choice)))))
1047 ;; for extra required elements, see if the spec includes a value for them
1048 (dolist (er create-extra)
1049 (let ((name (concat ":" (symbol-name er)))
1050 (keys (loop for i below (length spec) by 2
1051 collect (nth i spec))))
1053 (when (equal (symbol-name k) name)
1054 (aput 'valist er (plist-get spec k))))))
1056 ;; for each required element
1057 (dolist (r required)
1058 (let* ((data (aget valist r))
1059 ;; take the first element if the data is a list
1060 (data (auth-source-netrc-element-or-first data))
1061 ;; this is the default to be offered
1062 (given-default (aget auth-source-creation-defaults r))
1063 ;; the default supplementals are simple:
1064 ;; for the user, try `given-default' and then (user-login-name);
1065 ;; otherwise take `given-default'
1067 ((and (not given-default) (eq r 'user))
1070 (printable-defaults (list
1073 (auth-source-netrc-element-or-first
1074 (aget valist 'user))
1075 (plist-get artificial :user)
1079 (auth-source-netrc-element-or-first
1080 (aget valist 'host))
1081 (plist-get artificial :host)
1085 (auth-source-netrc-element-or-first
1086 (aget valist 'port))
1087 (plist-get artificial :port)
1089 (prompt (or (aget auth-source-creation-prompts r)
1091 (secret "%p password for %u@%h: ")
1092 (user "%p user name for %h: ")
1093 (host "%p host name for user %u: ")
1094 (port "%p port for %u@%h: "))
1095 (format "Enter %s (%%u@%%h:%%p): " r)))
1096 (prompt (auth-source-format-prompt
1098 `((?u ,(aget printable-defaults 'user))
1099 (?h ,(aget printable-defaults 'host))
1100 (?p ,(aget printable-defaults 'port))))))
1102 ;; store the data, prompting for the password if needed
1105 ((and (null data) (eq r 'secret))
1106 ;; special case prompt for passwords
1107 (read-passwd prompt))
1109 (read-string prompt 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
1135 ('secret "password")
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 '("nonesuch") :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'."
1156 (when (file-exists-p file)
1157 (insert-file-contents file))
1158 (when auth-source-gpg-encrypt-to
1159 ;; (see bug#7487) making `epa-file-encrypt-to' local to
1160 ;; this buffer lets epa-file skip the key selection query
1161 ;; (see the `local-variable-p' check in
1162 ;; `epa-file-write-region').
1163 (unless (local-variable-p 'epa-file-encrypt-to (current-buffer))
1164 (make-local-variable 'epa-file-encrypt-to))
1165 (if (listp auth-source-gpg-encrypt-to)
1166 (setq epa-file-encrypt-to auth-source-gpg-encrypt-to)))
1167 ;; we want the new data to be found first, so insert at beginning
1168 (goto-char (point-min))
1170 ;; ask AFTER we've successfully opened the file
1171 (let ((prompt (format "Save auth info to file %s? " file))
1172 (done (not (eq auth-source-save-behavior 'ask)))
1173 (bufname "*auth-source Help*")
1176 (setq k (auth-source-read-char-choice prompt '(?y ?n ?N ?e ??)))
1180 (with-output-to-temp-buffer bufname
1182 (concat "(y)es, save\n"
1183 "(n)o but use the info\n"
1184 "(N)o and don't ask to save again\n"
1186 "(?) for help as you can see.\n"))
1187 (set-buffer standard-output)
1193 auth-source-save-behavior nil))
1194 (?e (setq add (read-string "Line to add: " add)))
1197 (when (get-buffer-window bufname)
1198 (delete-window (get-buffer-window bufname)))
1200 ;; make sure the info is not saved
1201 (when (null auth-source-save-behavior)
1204 (when (< 0 (length add))
1209 (write-region (point-min) (point-max) file nil 'silent)
1210 (auth-source-do-debug
1211 "auth-source-netrc-create: wrote 1 new line to %s"
1213 (message "Saved new authentication information to %s" file)
1216 ;;; Backend specific parsing: Secrets API backend
1218 ;;; (let ((auth-sources '(default))) (auth-source-search :max 1 :create t))
1219 ;;; (let ((auth-sources '(default))) (auth-source-search :max 1 :delete t))
1220 ;;; (let ((auth-sources '(default))) (auth-source-search :max 1))
1221 ;;; (let ((auth-sources '(default))) (auth-source-search))
1222 ;;; (let ((auth-sources '("secrets:Login"))) (auth-source-search :max 1))
1223 ;;; (let ((auth-sources '("secrets:Login"))) (auth-source-search :max 1 :signon_realm "https://git.gnus.org/Git"))
1225 (defun* auth-source-secrets-search (&rest
1227 &key backend create delete label
1228 type max host user port
1230 "Search the Secrets API; spec is like `auth-source'.
1232 The :label key specifies the item's label. It is the only key
1233 that can specify a substring. Any :label value besides a string
1234 will allow any label.
1236 All other search keys must match exactly. If you need substring
1237 matching, do a wider search and narrow it down yourself.
1239 You'll get back all the properties of the token as a plist.
1241 Here's an example that looks for the first item in the 'Login'
1244 \(let ((auth-sources '(\"secrets:Login\")))
1245 (auth-source-search :max 1)
1247 Here's another that looks for the first item in the 'Login'
1248 Secrets collection whose label contains 'gnus':
1250 \(let ((auth-sources '(\"secrets:Login\")))
1251 (auth-source-search :max 1 :label \"gnus\")
1253 And this one looks for the first item in the 'Login' Secrets
1254 collection that's a Google Chrome entry for the git.gnus.org site
1255 authentication tokens:
1257 \(let ((auth-sources '(\"secrets:Login\")))
1258 (auth-source-search :max 1 :signon_realm \"https://git.gnus.org/Git\"))
1262 (assert (not create) nil
1263 "The Secrets API auth-source backend doesn't support creation yet")
1265 ;; (secrets-delete-item coll elt)
1266 (assert (not delete) nil
1267 "The Secrets API auth-source backend doesn't support deletion yet")
1269 (let* ((coll (oref backend source))
1270 (max (or max 5000)) ; sanity check: default to stop at 5K
1271 (ignored-keys '(:create :delete :max :backend :label))
1272 (search-keys (loop for i below (length spec) by 2
1273 unless (memq (nth i spec) ignored-keys)
1274 collect (nth i spec)))
1275 ;; build a search spec without the ignored keys
1276 ;; if a search key is nil or t (match anything), we skip it
1277 (search-spec (apply 'append (mapcar
1279 (if (or (null (plist-get spec k))
1280 (eq t (plist-get spec k)))
1282 (list k (plist-get spec k))))
1284 ;; needed keys (always including host, login, port, and secret)
1285 (returned-keys (mm-delete-duplicates (append
1286 '(:host :login :port :secret)
1288 (items (loop for item in (apply 'secrets-search-items coll search-spec)
1289 unless (and (stringp label)
1290 (not (string-match label item)))
1292 ;; TODO: respect max in `secrets-search-items', not after the fact
1293 (items (butlast items (- (length items) max)))
1294 ;; convert the item name to a full plist
1295 (items (mapcar (lambda (item)
1297 ;; make an entry for the secret (password) element
1300 (lexical-let ((v (secrets-get-secret coll item)))
1302 ;; rewrite the entry from ((k1 v1) (k2 v2)) to plist
1304 (mapcar (lambda (entry)
1305 (list (car entry) (cdr entry)))
1306 (secrets-get-attributes coll item)))))
1308 ;; ensure each item has each key in `returned-keys'
1309 (items (mapcar (lambda (plist)
1312 (mapcar (lambda (req)
1313 (if (plist-get plist req)
1321 (defun* auth-source-secrets-create (&rest
1323 &key backend type max host user port
1326 ;; (apply 'secrets-create-item (auth-get-source entry) name passwd spec)
1331 ;;; (auth-source-user-or-password '("login" "password") "imap.myhost.com" t "tzz")
1333 ;; deprecate the old interface
1334 (make-obsolete 'auth-source-user-or-password
1335 'auth-source-search "Emacs 24.1")
1336 (make-obsolete 'auth-source-forget-user-or-password
1337 'auth-source-forget "Emacs 24.1")
1339 (defun auth-source-user-or-password
1340 (mode host port &optional username create-missing delete-existing)
1341 "Find MODE (string or list of strings) matching HOST and PORT.
1343 DEPRECATED in favor of `auth-source-search'!
1345 USERNAME is optional and will be used as \"login\" in a search
1346 across the Secret Service API (see secrets.el) if the resulting
1347 items don't have a username. This means that if you search for
1348 username \"joe\" and it matches an item but the item doesn't have
1349 a :user attribute, the username \"joe\" will be returned.
1351 A non nil DELETE-EXISTING means deleting any matching password
1352 entry in the respective sources. This is useful only when
1353 CREATE-MISSING is non nil as well; the intended use case is to
1354 remove wrong password entries.
1356 If no matching entry is found, and CREATE-MISSING is non nil,
1357 the password will be retrieved interactively, and it will be
1358 stored in the password database which matches best (see
1361 MODE can be \"login\" or \"password\"."
1362 (auth-source-do-debug
1363 "auth-source-user-or-password: DEPRECATED get %s for %s (%s) + user=%s"
1364 mode host port username)
1366 (let* ((listy (listp mode))
1367 (mode (if listy mode (list mode)))
1369 (format "%s %s:%s %s" mode host port username)
1370 (format "%s %s:%s" mode host port)))
1371 (search (list :host host :port port))
1372 (search (if username (append search (list :user username)) search))
1373 (search (if create-missing
1374 (append search (list :create t))
1376 (search (if delete-existing
1377 (append search (list :delete t))
1379 ;; (found (if (not delete-existing)
1380 ;; (gethash cname auth-source-cache)
1381 ;; (remhash cname auth-source-cache)
1386 (auth-source-do-debug
1387 "auth-source-user-or-password: DEPRECATED cached %s=%s for %s (%s) + %s"
1389 ;; don't show the password
1390 (if (and (member "password" mode) t)
1394 found) ; return the found data
1395 ;; else, if not found, search with a max of 1
1396 (let ((choice (nth 0 (apply 'auth-source-search
1397 (append '(:max 1) search)))))
1401 ((equal "password" m)
1402 (push (if (plist-get choice :secret)
1403 (funcall (plist-get choice :secret))
1406 (push (plist-get choice :user) found)))))
1407 (setq found (nreverse found))
1408 (setq found (if listy found (car-safe found)))))
1412 (provide 'auth-source)
1414 ;;; auth-source.el ends here